2017-06-15 75 views
0
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() 

为什么这个代码导致错误蟒蛇线程(join()方法而不是等待线程结束?)

*********************************************** 
############################################### 
Traceback (most recent call last): 
    File "xxxxxxxxxxxxxxxxxxxxx", line 16, in <module> 
    a.start() 
RuntimeError: threads can only be started once 

应该不会加入()等到线程完成。如果我有误解怎么加入()的作品,我应该如何等待线程不使用超时

+0

你的代码改成这样 ** 而(真): 一个线程=(目标= s_process) a.start() a.join() ** – Stack

+1

的错误不是在'加入'行,它在'start'行。对我来说这似乎不言自明:不要在同一个对象上调用两次'start'。如果必须创建一个新的线程对象。 – Kevin

+0

您只定义了1个线程'a',并且您已经开始并称其为join()方法。不能再次启动它! – pstatix

回答

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 
+0

创建如此多的线程对象是否安全?他们会乱用内存使用情况吗?或者他们在完成后得到清理 – confusedsnek

+0

** del a **将清理 – Stack

+0

,但此方法一次创建1个线程。那么创建1个线程有什么意义?为什么不直接调用's_process'? –

0

要启动多个线程,建立threading.Thread对象的列表和使用for圈像这样重申他们start()join()方法:

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 0 Inlcuded,并用通用的Ctrl + X + C进行测试。

+0

我需要循环相同的代码,而不会在执行中途中断。KeyboardInterrupt – confusedsnek

+1

编辑包括现在针对您的线程的异常处理。 – pstatix