我第一次使用線程類中的線程,並且它們在函數運行後似乎沒有被釋放。我試圖一次運行最多5個線程。由於一個線程創建下一個會有一些重疊,但我看到2000+線程同時運行,然後我得到異常「無法啓動新線程」。Python釋放線程
from threading import Thread
import string
URLS = ['LONG LIST OF URLS HERE']
currentThread = 0
LASTTHREAD = len(URLS) - 1
MAXTHREADS = 5
threads = [None] * (LASTTHREAD + 1)
def getURL(threadName, currentThread):
print('Thread Name = ' + threadName)
print('URL = ' + str(URLS[currentThread]))
if currentThread < LASTTHREAD:
currentThread = currentThread + 1
thisThread = currentThread
try:
threads[thisThread] = Thread(target = getURL, args = ('thread' + str(thisThread), currentThread,))
threads[thisThread].start()
threads[thisThread].join()
except Exception,e:
print "Error: unable to start thread"
print str(e)
for i in range(0, MAXTHREADS):
currentThread = currentThread + 1
try:
threads[i] = Thread(target = getURL, args = ('thread' + str(i), currentThread,))
threads[i].start()
threads[i].join()
except Exception,e:
print "Error: unable to start thread"
print str(e)
我接受任何其他清理我可以在這裏做,以及因爲我是很新,Python和全新的穿線。我只是試圖在此時正確設置線程。最終這將刮擦URLS。
讓你的衍生線程自己產生線程是相當不尋常的。我建議在最低限度的重構,以便您的主線程完成所有的產卵。 – eddiewould