One - One Code All

Blog Content

python之多进程(multiprocess)

Python   2014-08-15 23:09:35

python多进程

#导入模块
from multiprocessing import Pool
import time,os,random
 
#创建一个测试函数subFunc
def subFunc(param,ppid):
    sleepTime = random.randint(1,10)
    print('Begin %s subProcess,and will wait %s,subPID is %s,mainPID is %s'%(param,sleepTime,os.getpid(),ppid))
    time.sleep(sleepTime)
    print('End %s subProcess...'%param)
 
if __name__ == '__main__':
    param = 5
    print('Begin mainProcess...')
    #创建进程池
    p = Pool(5)
    for i in range(param):
        p.apply_async(subFunc,args=(i+1,os.getpid(),))
    #关闭进程
    p.close()
    #等待子进程结束后在执行后续命令
    p.join()
 
    print('End mainProcess...')


示例2

#coding: utf-8
import multiprocessing

def m1(x):
    return(x*x)

if __name__ == '__main__':
    pool = multiprocessing.Pool(multiprocessing.cpu_count())
    i_list = range(8)
    res = pool.map(m1, i_list)
    pool.close()
    pool.join()
    print(res)



上一篇:airflow执行dag,trigger_dag
下一篇:更换npm源

The minute you think of giving up, think of the reason why you held on so long.