2017-08-11 9 views
1

で何も出力を与えない。ここに私のコードです:は、スレッドは、Python 3.6

import _thread 
import time 
def print_time(name, delay): 
    count=1 
    while count<=5: 
     time.delay(delay) 
     print ("Thread %s Time is %s"%(count, time.ctime(time.time()))) 
     count = count+1 

_thread.start_new_thread(print_time,("T-1",2)) 
_thread.start_new_thread(print_time,("T-2",4)) 

出力は、現在の時刻を伝える様々なラインでなければなりません。しかし、プログラムを実行した後、出力は得られずエラーもなくなりました。なぜこうなった?私はPython 3.6を使用しています。

+0

私はインポートする必要がありますどのモジュールwhackmadoodle3000 @マルチプロセシングライブラリ –

+0

を使用しますか? –

+0

マルチプロセッシングhttps://docs.python.org/2/library/multiprocessing.html –

答えて

1

おそらく最初の質問は_threadを使用している理由です。あなたの問題は、print_timeが出力を生成する前にメインスレッドが終了していることを推測しています。この特定のシステムでは、プログラム全体が終了します。 _thread documentationのセクション警告から

When the main thread exits, it is system defined whether the other threads survive. On most systems, they are killed without executing tryfinally clauses or executing object destructors.

代わりthreadingを使用している場合、あなたはdaemon引数でスレッドを待機するかどうかを選択してもらいます。

+0

'thread'モジュールを使用できませんか?私は現在、プロキシサーバーを学習しており、 'thread'モジュールを使用しています。 –

+0

確かにあなたは注意を払い、すべての細部を扱わなければなりません。あるいは、既にそれを行っている標準ライブラリ内のモジュールを使用することもできます。この場合、(すべてのスレッドをメインスレッドに参加させるという形で)暗黙的な同期が期待されましたが、明示的にする必要がありました。 –

+0

私のシステムは 'ImportError:no module named thread'と言っています。私は何をすべきか? –

0

使用threading

import threading 
import time 

def print_time(name, delay): 
    count=1 
    while count<=5: 
     time.sleep(delay) 
     print ("Thread %s Time is %s"%(count, time.ctime(time.time()))) 
     count = count+1 

t1 = threading.Thread(target=print_time, args=("T-1",2)) 
t2 = threading.Thread(target=print_time, args=("T-2",4)) 

t1.start() 
t2.start() 

The threading module provides an easier to use and higher-level threading API built on top of this [ _thread ] module.