[英]Threading Gives No Output in 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。
第一個問題可能是你為什么使用_thread
。 我猜你的問題是你的主線程在print_time
設法產生任何輸出之前完成,並且在這個特定的系統上,退出整個程序。
從_thread 文檔中的警告部分:
當主線程退出時,其他線程是否存活由系統定義。 在大多數系統上,它們會在不執行
try
...finally
子句或執行對象析構函數的情況下被殺死。
當改用threading
,您可以選擇是否使用daemon
參數等待線程。
上面的答案總是更好的選擇,但如果你仍然堅持使用_thread
模塊,只需在代碼末尾添加time.sleep(1)
延遲主線程
使用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()
threading 模塊提供了一個更易於使用和更高級別的線程 API,它構建在這個 [
_thread
] 模塊_thread
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.