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)
最佳答案
工作解决方案发布在下面。 基本思想是我们只声明与可用 CPU 一样多的线程实例。然后我们继续将“任务”(或此处的“事物”)添加到队列中。 一旦任务被添加到队列中,我们在上一步中声明的 Thread 实例之一就会立即拾取它。
重要提示:为了使此机制正常工作,MyThread.run()
方法应该在 while
循环内运行。否则 MyThread 实例将在完成第一个任务后立即终止。当队列中没有任务剩余时,while
循环将自行退出。故事就这样结束了。
import Queue
import threading, time
class MyThread(threading.Thread):
def __init__(self, theQueue=None):
threading.Thread.__init__(self)
self.theQueue=theQueue
def run(self):
while True:
thing=self.theQueue.get()
self.process(thing)
self.theQueue.task_done()
def process(self, thing):
time.sleep(1)
print 'processing %s'%thing
queue=Queue.Queue()
THINGS = ['Thing%02d'%i for i in range(101)]
AVAILABLE_CPUS=3
for OneOf in range(AVAILABLE_CPUS):
thread=MyThread(theQueue=queue)
thread.start() # thread started. But since there are no tasks in Queue yet it is just waiting.
for thing in THINGS:
queue.put(thing) # as soon as task in added here one of available Threads picks it up
关于python - 如何限制线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951763/