私はこのコードを持っている:複数のスレッドを使用する方法
私は10個のスレッドを作成したいimport thread
def print_out(m1, m2):
print m1
print m2
print "\n"
for num in range(0, 10):
thread.start_new_thread(print_out, ('a', 'b'))
、各スレッドが機能print_out
を実行するが、私は失敗しました。次のようにエラーがあります:すべての
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
'thread.join()'は、スレッドが終了するまで待機するために使用されます。スレッドのスレッド:thread.join() 'の最後の2行を追加しないと、プログラムもうまく実行され、すべてのスレッドが' thread.start() 'でデバッグに従って実行されることに気付きました私は 'time.time(0.1)'を追加しないと、 'thread.join()'というコードを追加する必要はありません。なぜなら、プログラムはスレッドを自動的に 'thread.start()'で終了させるからです。 – Searene
@マーク 'time.sleep(0.1)'はまったく追加する必要はありません。それだけでは必要ありません。はい、 'join'を呼び出すコードを削除することができ、Python環境は実行を終了する前にすべてのスレッドが完了するのを待ちます。しかし、スレッドの実行を待つ方法を知っておく必要があると私は期待しているので、 'join 'への呼び出しを追加しました。しかし、この簡単な例では、 'join'への呼び出しを単に省略することができます。 –