2016-04-30 57 views
2

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) 
+2

的可能的复制[正确的方法来限制同时运行的最大线程数?(http://stackoverflow.com/questions/19369724/the-right-way-to-limit-maximum-number线程运行在一次) – Morishiri

+1

看起来像一个池.. https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers – Olegp

+0

我不知道我们是否可以将活动线程的数量限制在12'。制作12个线程。不要再做了。不要让他们中的任何一个终止。 –

回答

3

该工作解决方案发布如下。 其基本思想是我们只声明与可用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 
+2

明智的答案!很有帮助。唯一没有为我工作的代码永远不会终止,所以我使用'while notQueue.empty():'而不是'while True'。为了做到这一点,我在用'AVAILABLE_CPUS'运行'for'循环之前用'THIINGS'运行'for'循环,否则线程会立即终止,因为myQueue是空的。 – Andras