2014-01-15 71 views
1

我想在python中創建3個線程,我正在使用python類線程庫, 下面是在while循環中創建線程的正確方法嗎?它可能會產生問題?在python中創建許多線程?

while (count <= 3): 
    try: 
     thread = CreateThread(count, args) 
     thread.start() 
    except: 
     logger.error("Error: unable to start thread ") 

任何其他正確的方法?

+0

看起來像你的問題是不是真的在這裏定義。請過濾你的問題並告訴我們問題。 根據你對@Serdalis的評論回答,你有一個問題連接到你的路由器多次,而不是一個問題開始線程。請記住,大多數塑料路由器都有連接限制。 –

回答

3

雖然我們無法看到您的實際Thread類,但我會認爲它是正確的,但在此代碼中有一些可以改進的地方。

您需要保留對每個線程的引用,以便您可以在稍後停止/加入/等待它們。

所以,你的代碼應該看起來更像是:

thread = [] 
for i in range(3): 
    try: 
     new_thread = CoreRouterThread(count, args) 
     new_thread.start() 
     # we append the thread here so we don't get any failed threads in the list. 
     thread.append(new_thread) 
    except: 
     logger.error("Error: unable to start thread ") 
+0

謝謝serdalis ...每個線程用於連接到路由器和獲取數據...由於這個循環導致任何問題?..我正在通過對等錯誤 –

+0

得到連接重置這樣的循環應該不會導致問題。你得到這個錯誤是因爲[服務器不想和你說話](http://stackoverflow.com/questions/1434451/what-does-connection-reset-by-peer-mean)出於任何原因。您的網絡編碼或網絡配置可能有問題。 – Serdalis