gpt4 book ai didi

python - 如何知道 threading.Condition.wait(timeout) 是否已超时或已通知?

转载 作者:太空狗 更新时间:2023-10-30 00:10:32 25 4
gpt4 key购买 nike

我正在开发一个包含一些线程的应用程序,每个线程都运行一个无限循环并有一段时间休眠。我想要的是在主线程完成后完成所有线程,这里有一个例子:

def main():

display_res_stop = threading.Condition()
display_result_t = threading.Thread(target=sample_t, args=(display_res_stop, ))
display_result_t.start()

time.sleep(4)

display_res_stop.acquire()
display_res_stop.notify()
display_res_stop.release()


def sample_t(stop_cond):
stop_cond.acquire()

while True:
print 5
c = stop_cond.wait(10)

stop_cond.release()

if __name__ == '__main__':
main()

这个解决方案的问题是,我不知道condition.wait是否已经完成,因为超时或者因为已经被通知。在第二种情况下,while 循环应该结束。

起初我在做一个 time.sleep(t) 并使用线程事件,但随后应用程序必须等到所有线程上的 t 都过去了。

我正在考虑使用 threading.Condition 和 Event 的混合解决方案,但我不知道这是否是最好的做法(“ sleep ”条件和事件在 True 时替换)。

最佳答案

毕竟它非常简单,我只是专注于错误的事情:我只需要一个可以通过事件停止的 sleep ,这就是 Event.wait(t) 所做的。那么问题就可以通过事件来解决。

import threading
import time

def sample_thread(stop_ev):
while not stop_ev.is_set():
print 'Thread iteration'
stop_ev.wait(0.1)

def main():
stop_ev = threading.Event()
sample_t = threading.Thread(target=sample_thread, args=(stop_ev, ))
sample_t.start()

# Other stuff here, sleep is just dummy
time.sleep(14)

stop_ev.set()

print 'End reached.'

if __name__ == '__main__':
main()

关于python - 如何知道 threading.Condition.wait(timeout) 是否已超时或已通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29937546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com