2013-02-28 66 views
0

使用这个非常简单的例子,我可以如何限制进程每次5,而不是同时处理所有的90?多进程限制进程

import multiprocessing 

def worker(num): 
    """thread worker function""" 
    print 'Worker:', num 
    return 

if __name__ == '__main__': 
    jobs = [] 
    for i in range(90): 
     p = multiprocessing.Process(target=worker, args=(i,)) 
     jobs.append(p) 
     p.start() 

问候。

回答

3

检查文档:http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

的解决方案是创建5名工人的池(你的情况),并使用该池来处理每个请求。

如果你是合理的新Python和需要的线程和进程的介绍,我想这表现还算不错: http://www.slideshare.net/pvergain/multiprocessing-with-python-presentation

通过它,你会学到一些东西,并接近尾声你会得到一个使用Pools的例子。

+0

嗨, 我是新来的蟒蛇,你可以请给我一个例子,我怎样才能将你的建议应用于我的问题? – 2013-02-28 11:45:12

+0

感谢您给予与信息的链接,而不是回答完整的解决方案=) – 2013-02-28 14:25:16

1

multiprocessing.Pool是你所需要的

0

这是给你的任务与线程和队列就是一个例子5线长:

#!/usr/bin/env python 
import threading, Queue 

class ThreadedWorker(threading.Thread): 
     jobQueue = Queue.Queue() 

     def run(self): 
       while True: 
         num = ThreadedWorker.jobQueue.get() 

         """thread worker function""" 
         print 'Worker:', num 

         ThreadedWorker.jobQueue.task_done() 

class MainClass(ThreadedWorker): 
     def __init__(self): 
       self.maxThreads = 5 
       self.startTest() 

     def startTest(self): 
       meine_threads = [ThreadedWorker() for i in range(self.maxThreads)] 

       for thread in meine_threads: 
         thread.setDaemon(True) 
         thread.start() 

       for i in range(90): 
         ThreadedWorker.jobQueue.put(i) 

       ThreadedWorker.jobQueue.join() 

mc = MainClass()