【发布时间】:2017-06-15 22:34:37
【问题描述】:
import time
from threading import Thread
def s_process():
print('***********************************************')
##time.sleep(2)
print('###############################################')
##time.sleep(2)
return
a = Thread(target=s_process)
while(True):
a.start()
a.join()
a.start()
a.join()
为什么这段代码会导致错误
***********************************************
###############################################
Traceback (most recent call last):
File "xxxxxxxxxxxxxxxxxxxxx", line 16, in <module>
a.start()
RuntimeError: threads can only be started once
不应该 join() 等到线程完成。如果我误解了 join() 的工作原理,我应该如何在不使用超时的情况下等待线程完成
【问题讨论】:
-
把你的代码改成这个 ** while(True): a = Thread(target=s_process) a.start() a.join() **
-
错误不在
join行,它在start行。这对我来说似乎不言自明:不要在同一个对象上调用start两次。如果需要,创建一个新的线程对象。 -
您只定义了 1 个线程
a并且您已经开始并调用了它的join()方法。无法重新开始! -
创建这么多线程对象安全吗?他们会弄乱内存使用吗?还是在完成后清理干净
标签: python multithreading