2017-10-09 40 views
0

好吧,說我有這樣的代碼:如何使用Python 3的多處理池運行2個不同的函數?

import time 

def helloworld(sleep_time): 
    while True: 
     time.sleep(sleep_time) 
     print('Hello world!') 

def hellocountry(): 
    while True: 
     time.sleep(60) 
     print('Hello country!') 

if __name__ == '__main__': 
    with Pool(3) as p: 
     p.map(helloworld, [1, 5, 7]) 

我將如何執行hellocountry,而正在執行的HelloWorld?我想我可以編寫一個包裝函數,但這看起來相當笨拙和unpythonic。

+0

使用['.submit()'](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.submit)(I表示建議爲' helloworld()'也是這樣調用的)。 – Elazar

+0

那麼池()只是ThreadPoolExecutor的包裝? – user6769219

+0

在您的代碼中,「Pool」未定義。但是,不,我混淆了'Pool'和Executor。 – Elazar

回答

1

只需使用apply_async方法。

if __name__ == '__main__': 
    with Pool(3) as p: 
     p.apply_async(hellocountry) 
     p.map(helloworld, [1, 5, 7])