[英]Understanding threading
試圖讓我的頭腦繞線程。 在我的代碼中,它只觸發一個線程,當我認為它應該直接進入第二個。 我一直在閱讀有關鎖和分配的內容,但不太了解。 我需要做什么才能讓2個線程同時獨立運行?
import thread
def myproc(item):
print("Thread fired for " + item)
while True:
pass
things = ['thingone', 'thingtwo']
for thing in things:
try:
thread.start_new_thread(myproc(thing))
except:
print("Error")
你有start_new_thread
的簽名錯誤。 你正在調用myproc
並將結果作為參數傳遞給start_new_thread
,這從未發生,因為myproc
永遠不會終止。
相反,它應該是:
thread.start_new_thread(myproc, (thing,) )
第一個參數是函數(即函數對象,不調用函數),第二個參數是參數元組。
請參閱: https : //docs.python.org/2/library/thread.html#thread.start_new_thread
一旦你的程序實際啟動了兩個線程,你可能想在最后添加一個暫停,因為線程將在主線程完成時終止。
另外,請考慮使用threading
模塊而不是thread
模塊,因為它提供了更好的更高級別的接口,例如等待線程完成執行的便捷方式。
請參閱: https : //docs.python.org/2/library/threading.html#module-threading
根據我的判斷,您的應用程序在第二個線程有時間完成之前退出。
在應用程序終止之前,您需要等待兩個線程完成,如下所示:
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1: # This is a bad solution due to the busy wait loop. More below.
pass
您最好存儲線程對象,並在退出之前使用thread1.join()
和thread2.join()
,以表示它們已終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.