2017-10-09 38 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])