[英]Python Threading With Concurrency
我在嘗試學習python中的線程時編寫了以下代碼。
import threading
import time
def printWorker(x,y):
t = time.time()
while time.time() - t < 10:
print "Name:%s Time:%s" %(y,str(time.time() - t))
time.sleep(x)
t1 = threading.Thread(target = printWorker(2,'Thread-1'))
t2 = threading.Thread(target = printWorker(3,'Thread-2'))
t1.start()
t2.start()
我試圖得到一個輸出,其中Thread-1和Thread-2同時啟動。 IE打印
Thread-1 Stuff,Thread-2 Stuff,Thread-1 Stuff,Thread-2 Stuff,而不是
Thread-1 Stuff,Thread-1 Stuff,Thread-1 Stuff,Thread-1 Stuff,Thread-2 Stuff,Thread-2 Stuff,Thread-2 Stuff,Thread-2 Stuff
而是Thread-2僅在Thread-1之后啟動。 我已經檢查了在線示例,但我不明白我在機械上做錯了什么。
要傳遞參數,您需要這樣做:
t1 = threading.Thread(target=printWorker, args=(2, 'Thread-1'))
t2 = threading.Thread(target=printWorker, args=(3, 'Thread-2'))
您的代碼在主線程上調用printWorker並以target = None(printWorker的返回值)啟動兩個線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.