为什么python线程在等待时仍然运行?

2024-10-03 19:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我很好奇为什么下面代码中的while循环在我告诉它等待事件对象之后仍然运行。你知道吗

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()

我得到以下输出

second thread starting now..a

hello
0
hello
1
b
hello
2
hello
3
....
(keeps going)

我可以用注释掉的while循环修复它,但是我很好奇为什么它仍然运行。主线程已运行完毕,因此不应设置线程事件以允许第二个线程运行。你知道吗

谢谢你。你知道吗


Tags: hellotimecounter事件msgsleepsecthread
1条回答
网友
1楼 · 发布于 2024-10-03 19:30:31

由于msg已设置(您已设置),因此循环不需要等待。如果要使循环等待,请对事件调用clear。如果愿意,可以在msg.wait返回后进行循环调用msg.clear()。你知道吗

相关问题 更多 >