循环中的python线程导致运行时错误(join()没有等待线程结束?)

时间:2017-06-15 14:04:56

标签: python multithreading

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()是如何工作的,我应该如何等待线程完成而不使用超时

2 个答案:

答案 0 :(得分:0)

这应该有效:

import time
from threading import Thread

def s_process():
    print('***********************************************')
    ##time.sleep(2)
    print('###############################################')
    ##time.sleep(2)
    return

while(True):
    a = Thread(target=s_process)
    a.start()
    a.join()
    del a           #deletes a

答案 1 :(得分:0)

要启动多个线程,请构建threading.Thread个对象列表,并使用start()循环迭代其join()for方法,如下所示:

import time
from threading import Thread

def s_process():
    print('***********************************************')
    time.sleep(2)
    print('###############################################')
    time.sleep(2)
    return

# list comprehension that creates 2 threading.Thread objects
threads = [Thread(target=s_process) for x in range(0, 2)]

# starts thread 1
# joins thread 1
# starts thread 2
# joins thread 2
for thread in threads:
    try:
        thread.start()
        thread.join()
    except KeyboardInterrupt: # std Python exception
        continue # moves to next thread iterable

修改:为try/except包含KeyboardInterrupt并使用常规测试Ctrl + X + C进行测试。