I’m trying to synchronize multiple threads. I expect script output when using threading.Condition and threading.Barrier will be about the same, but it’s not. Please explain why this is happening.
In general, I need threads to perform work (some IO operation) in an infinite loop, but each cycle starts with the permission of the master thread, and permission is given only after the previous cycle is completed by all threads.
script 1
from threading import Barrier, Thread
from time import sleep, time
br = Barrier(3)
store = []
def f1():
while True:
br.wait()
sleep(1)
print("Calc part1")
def f2():
while True:
br.wait()
sleep(1)
print("Calc part2")
Thread(target=f1).start()
Thread(target=f2).start()
for i in range(10):
br.wait()
print(f'end iter {i}')
print(f'-------------')
expected behavior
ent iter 0
-------------
Calc part1
Calc part2
ent iter 1
-------------
Calc part1
Calc part2
ent iter 2
-------------
Calc part1
Calc part2
ent iter 3
-------------
Calc part1
script 2
from threading import Condition, Thread
from time import sleep
condition = False
cv = Condition()
def predicate():
return condition
def f1():
for i in range(3):
with cv:
cv.wait_for(predicate)
sleep(1)
print("Calc part1")
def f2():
for i in range(3):
with cv:
cv.wait_for(predicate)
sleep(1)
print("Calc part2")
Thread(target=f1).start()
Thread(target=f2).start()
with cv:
condition = True
cv.notify_all()
unexpected behavior
Calc part1
Calc part1
Calc part1
Calc part2
Calc part2
Calc part2
Why stdout of threads not mixed in result of second script?
eugeny is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.