Reputation: 711
I'm curious as to why the while loop in below code still runs after I told it to wait on a event object.
import threading, time
msg = threading.Event()
def sec():
print "second thread starting now.."
counter = 0
while True:
#while msg.isSet():
print "hello"
print counter
counter += 1
time.sleep(3)
msg.wait()
secThread = threading.Thread(target = sec)
secThread.start()
print "a"
msg.set()
time.sleep(5)
print "b"
msg.set()
And I get the following output
second thread starting now..a
hello
0
hello
1
b
hello
2
hello
3
....
(keeps going)
I can fix it with the commented out while loop, but I'm curious as to why it still ran. The main thread is done running so nothing should be setting the threading event to allow the second thread to run.
Thank you.
Upvotes: 0
Views: 184
Reputation: 182769
Since msg
is set (you set it), the loop does not need to wait. If you want to make the loop wait, call clear
on the event. You can make the loop call msg.clear()
after msg.wait
returns if you wish.
Upvotes: 2