2017-06-15 5 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() 

なぜ、このコードはエラーPythonのスレッド(参加()終了するスレッドを待っていない?)

*********************************************** 
############################################### 
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

エラーが上ではありません ' 'join'行では、' start'行にあります。私には自明のようです:同じオブジェクトに対して 'start'を2度コールしないでください。必要がある場合は、新しいスレッドオブジェクトを作成します。 – 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 

編集: Inlcuded try/except 0をするためにであり、一般的な使用Ctrl + X + Cでテストされています。

+0

実行中の途中で中断することなく、同じコードをループする必要がありますKeyboardInterrupt – confusedsnek

+1

編集にはスレッドの例外処理が含まれています。 – pstatix

関連する問題