【问题标题】:Why does python thread still run while waiting?为什么python线程在等待时仍然运行?
【发布时间】:2017-12-02 04:27:04
【问题描述】:

我很好奇为什么下面代码中的 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 循环来修复它,但我很好奇它为什么仍然运行。主线程已完成运行,因此不应设置线程事件以允许第二个线程运行。

谢谢。

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    由于设置了msg(你设置了它),循环不需要等待。如果您想让循环等待,请在事件上调用clear。如果您愿意,您可以在msg.wait 返回后进行循环调用msg.clear()

    【讨论】:

    • 知道了。我错误地认为“等待”会重置标志,但事实并非如此。要重新设置标志,我应该像你说的那样使用 clear 。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多