Jai*_*llo 6 python multithreading python-multithreading
我正在开发一个带有一些线程的应用程序,每个线程运行一个带有时间睡眠的无限循环.我想要的是在主要完成后完成所有线程,这里是一个例子:
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()
Run Code Online (Sandbox Code Playgroud)
这个解决方案的问题是我不知道condition.wait是否已经完成,因为超时或因为已经通知.在第二种情况下,while循环应该完成.
起初我正在做一个time.sleep(t)并使用线程事件但是应用程序必须等到所有线程都经过.
我正在考虑使用threading.Condition和Event的混合解决方案,但我不知道它是否是最好的事情(条件为'sleep'和Event替换为True).
毕竟这很简单,我只是专注于错误的事情:我只需要一个可以通过事件停止的睡眠,这就是 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()
Run Code Online (Sandbox Code Playgroud)