generated from justuser-31/code_projects_template
45 lines
873 B
Python
45 lines
873 B
Python
from threading import Thread
|
|
from queue import Queue
|
|
from time import sleep
|
|
|
|
sum = 0
|
|
access = 0 # Var for control who is allowed access for sum, start with 0 Thread
|
|
threads = 3
|
|
th_pool = []
|
|
is_live = [0] * threads
|
|
|
|
def worker(i):
|
|
global sum, access, threads, th_pool, is_live
|
|
th_pool.append(i)
|
|
is_live[i] = 1
|
|
# Wait until all threads is registred
|
|
while len(th_pool) != threads:
|
|
sleep(0.1)
|
|
for _ in range(3):
|
|
#sleep(threads)
|
|
while access != i:
|
|
sleep(0.1)
|
|
sum += 1
|
|
print(f'T{i} | {sum}')
|
|
sleep(0.1)
|
|
# Transfer access
|
|
if len(th_pool) > 1:
|
|
ind = th_pool.index(i)
|
|
next = ind + 1
|
|
if next > threads - 1:
|
|
next = 0
|
|
access = next
|
|
else:
|
|
access = i
|
|
is_live[i] = 0
|
|
|
|
for i in range(threads):
|
|
th = Thread(target = worker, args = (i,))
|
|
th.start()
|
|
|
|
# Wait untill all ended
|
|
while is_live != [0] * threads:
|
|
sleep(0.1)
|
|
|
|
print(f'\nSUM: {sum}')
|