【Python】multiprocessing多进程实例

本文通过实例展示了Python的multiprocessing模块实现多进程的方法,包括pool+map和直接使用Process。强调了在多进程编程中需要注意的事项,如进程终结后需调用wait或join以防止僵尸进程,以及避免在多进程中直接共享资源。推荐使用Pipe和Queue进行进程间通信以提高效率。此外,介绍了Process对象的PID属性和一个使用Queue的多进程案例。
摘要由CSDN通过智能技术生成

以下代码亲测可运行,环境py3.5

案例1:使用多进程的pool+map

# coding:utf-8
import multiprocessing

def f(x):
    return x * x

if __name__ == "__main__":
    cores = multiprocessing.cpu_count()
    pool = multiprocessing.Pool(processes=cores)
    xs = range(5)
    
    # method 1: map
    print(pool.map(f, xs))  # prints [0, 1, 4, 9, 16]
    
    # method 2: imap
    for y in pool.imap(f, xs):
        print(y)            # 0, 1, 4, 9, 16, respectively
    
    # method 3: imap_unordered
    for y in pool.imap_unordered(f, xs):
        print(y)           # may be in any order
        
    cnt = 0
    for _ in pool.imap_unordered(f, xs):
        sys.stdout.write('done %d/%d\r' % (cnt, len(xs)))
        cnt += 1

或者


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值