2017-02-21 26 views
0

所以我也有類似的這種Python的多重啓動一批工人,並開始別人當一個完成

import multiprocessing 

class MyFancyClass(object): 

    def __init__(self, name): 
    self.name = name 

    def do_something(self): 
    proc_name = multiprocessing.current_process().name 
    print 'Doing something fancy in %s for %s!' % (proc_name, self.name) 


def worker(q): 
    obj = q.get() 
    obj.do_something() 


if __name__ == '__main__': 
     urls = [ 
    'http://www.python.org', 
    'http://www.python.org/about/', 
    'http://www.python.org/community/awards/' 
    # etc.. 
] 

    queue = multiprocessing.Queue() 

    p = multiprocessing.Process(target=worker, args=(queue,)) 
    p.start() 

    queue.put(MyFancyClass('Fancy Dan')) 

    # Wait for the worker to finish 
    queue.close() 
    queue.join_thread() 
    p.join() 

我想要做的是有4個或更多的「工人」是什麼東西啓動和處理的URL,當一個完成開始另一個。 什麼是最好的方式來做到這一點。我花了兩天時間,無法弄清楚。

謝謝 謝謝。

+0

您應該使用進程池。在這裏閱讀更多 https://docs.python.org/2/library/multiprocessing.html – AndreyF

+0

你能給我一個如何與類一起使用的例子嗎? – sfantu

+0

https://www.pythonsheets.com/notes/python-concurrency.html - 用於作爲包括多處理在內的各種並行處理的模板的範例程序 – gregory

回答

2

使用concurrent.futures

import concurrent.futures 
import multiprocessing 

def do_something(name): 
    proc_name = multiprocessing.current_process().name 
    print 'Doing something fancy in %s for %s!' % (proc_name, name) 

class MyFancyClass(object): 

    def __init__(self, name): 
    self.name = name 


MyFancy = MyFancyClass("Name") 

if __name__ == '__main__': 
    urls = [ 
     'http://www.python.org', 
     'http://www.python.org/about/', 
     'http://www.python.org/community/awards/' 
     # etc.. 
] 

with concurrent.futures.ProcessPoolExecutor() as executor: 
    results = executor.map(do_something, urls) 

concurrent.futures documentation瞭解詳情。

+0

NameError:名稱'do_something'未定義 – sfantu

+1

您需要集成代碼與你的上面。我會更新我的答案。 – AJPennster

+0

PicklingError:不能pickle :屬性查找__builtin __。instancemethod失敗 – sfantu

1

無需發明車輪。 ProcessPoolExecutorconcurrent.futures完全符合您的需求。

0

使用Poolmultiprocessing

下面是可能適合你的目的很短的使用例子:

from multiprocessing import Pool 

def f(x,y): 
    print x*y 

p = Pool(5) 
for i in range(100): 
    p.apply_async(f,(i,i+1)) 
p.close() 
p.join() 
相關問題