2016-04-30 98 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