看看thread.join()
方法。基本上它會阻止你的調用線程,直到子線程返回(從而阻止它在它應該之前退出)。
更新:
爲了避免你的主線程沒有反應,你可以使用while循環的新要求。
while threading.active_count() > 0:
# ... look for new requests to handle ...
time.sleep(0.1)
# or try joining your threads with a timeout
#for thread in my_threads:
# thread.join(0.1)
更新2:
它也像thread.start_new(func, args)
是obsolete。它被更新爲thread.start_new_thread(function, args[, kwargs])
您還可以創建線程與更高級別的線程包(這是一個讓您得到在前面的代碼塊中的active_count()
包):
import threading
my_thread = threading.Thread(target=func, args=(), kwargs={})
my_thread.daemon = True
my_thread.start()
這可能會起作用,但是當以FastCGI的方式運行時,是不是會阻止腳本處理新的請求? – crgwbr 2010-05-17 16:17:40
我從來沒有使用FastCGI,但可能。你可以做的是把連接放在一個while循環中,並給它一個超時,所以它試圖加入線程,超時並尋找新的請求。 – tgray 2010-05-17 16:33:28
將它設置爲一個守護進程看起來好像會起作用。我沒有意識到'start_new'已被棄用。 謝謝 – crgwbr 2010-05-17 17:33:29