python 多进程示例

示例1:

from  multiprocessing import Pool
import time


def Foo(i):
    time.sleep(2)
    return i + 100

def Bar(arg):
    return arg

if __name__ == '__main__':
    res_list=[]
    t_start=time.time()
    pool = Pool(10)

    for i in range(10):
        res = pool.apply_async(func=Foo, args=(i,), callback=Bar)
        res_list.append(res)

    pool.close()
    pool.join()
    for res in res_list:
        print(res.get())
    t_end=time.time()
    t=t_end-t_start
    print('the program time is :%s' %t)

示例2:

from multiprocessing import Pool

def f(x):
    return x*x

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

参考资料:
https://docs.python.org/zh-cn/3/library/multiprocessing.html#the-process-class

你可能感兴趣的:(python,python,开发语言)