[英]Can't start new thread
我正在使用多個線程處理目錄中的所有文件以並行處理文件。 一切正常,除了線程似乎保持活着,因此進程的線程數一直上升,直到它達到1K左右的線程,然后它拋出一個thread.error can't start new thread
錯誤。 我知道這個錯誤是由線程數的操作系統級別限制引起的。 我似乎無法弄清楚錯誤的位置是保持線程活着。 任何的想法? 這是我的代碼的最小版本。
class Worker(Thread):
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try:
func(*args, **kargs)
except Exception, e: print e
self.tasks.task_done()
class ThreadPool:
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
self.tasks.put((func, args, kargs))
def wait_completion(self):
self.tasks.join()
def foo(filename)
pool = ThreadPool(32)
iterable_data = process_file(filename)
for data in iterable_data:
pool.add_task(some_function, data)
pool.wait_completion()
files = os.listdir(directory)
for file in files:
foo(file)
您正在為每個文件啟動一個包含32個線程的新ThreadPool。 如果你有大量的文件,那將是很多線程。 並且由於CPython中一次只能有一個線程執行Python字節碼(因為全局解釋器鎖定),因此它不一定非常快。
將ThreadPool的創建移到foo()
函數之外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.