在THINGS
变量中存储了101件事情。 该代码声明了101个线程,并立即全部同时立即执行它们。如何限制线程数
我不知道,如果我们能够有效的线程数限制为仅12
起初只有12个线程应该选择自己的12件实事来处理。其余的线程应该等待前12名完成他们的工作。当前12个线程全部完成时,接下来的12个线程将接下来处理的12个线程。还有一个。
会有可能吗?
import Queue
import threading, time
class MyThread(threading.Thread):
def __init__(self, theQueue=None):
threading.Thread.__init__(self)
self.theQueue=theQueue
def run(self):
thing=self.theQueue.get()
self.process(thing)
self.theQueue.task_done()
def process(self, thing):
time.sleep(1)
print 'processing %s'%thing.name
queue=Queue.Queue()
THINGS = ['Thing%02d'%i for i in range(101)]
THREADS=[]
for thing in THINGS:
thread=MyThread(theQueue=queue)
thread.name = thing
THREADS.append(thread)
thread.start()
for thread in THREADS:
queue.put(thread)
的可能的复制[正确的方法来限制同时运行的最大线程数?(http://stackoverflow.com/questions/19369724/the-right-way-to-limit-maximum-number线程运行在一次) – Morishiri
看起来像一个池.. https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers – Olegp
我不知道我们是否可以将活动线程的数量限制在12'。制作12个线程。不要再做了。不要让他们中的任何一个终止。 –