python进程池

串行进程池:

from multiprocessing import Process,Pool,freeze_support
import time
import os

def f(i):
    time.sleep(2)
    print('in process:',os.getpid())
    return i+100

def b(arg):
    print(arg)

if __name__ == '__main__': #运行当前模块时会执行该代码,其他模块导入该模块是不执行该段代码
    # freeze_support()
    pool = Pool(5)#允许进程池里同时放入5个进程
    for i in range(10):
        pool.apply(func=f,args=(i,))#串行
        
    print('end')
    pool.close()

并行进程池:

from multiprocessing import Process,Pool,freeze_support
import time
import os

def f(i):
    time.sleep(2)
    print('in process:',os.getpid())
    return i+100

def b(arg):
    print(arg)

if __name__ == '__main__': #运行当前模块时会执行该代码,其他模块导入该模块是不执行该段代码
    # freeze_support()
    pool = Pool(5)#允许进程池里同时放入5个进程
    for i in range(10):
        pool.apply_async(func=f,args=(i,))#并行
    print('end')
    pool.close()
    pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭

在并行池中必须先close再join,不然打印end后就直接结束了,进程池中的进程还未执行完毕

进程池回调:

from multiprocessing import Process,Pool,freeze_support
import time
import os

def f(i):
    time.sleep(2)
    print('in process:',os.getpid())
    return i+100

def b(arg):
    print(arg,os.getpid())

if __name__ == '__main__': #运行当前模块时会执行该代码,其他模块导入该模块是不执行该段代码
    # freeze_support()
    pool = Pool(5)#允许进程池里同时放入5个进程
    print('main process pid:',os.getpid())
    for i in range(10):
        pool.apply_async(func=f, args=(i,),callback=b)#callback回调,机执行完func=f后再执行b函数
    print('end')
    pool.close()
    pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭
main process pid: 9348
end
in process: 9516
100 9348
in process: 4928
101 9348
in process: 9536
102 9348
in process: 9948
103 9348
in process: 7728
104 9348
in process: 9516
105 9348
in process: 4928
106 9348
in process: 9536
107 9348
in process: 9948
108 9348
in process: 7728
109 9348

回调函数均是在主进程里面执行的

你可能感兴趣的:(python进程池)