Python 进程池与进程锁

#coding:utf-8

import time
import os
import multiprocessing

def work(count):
    print(count,',进程id:',os.getpid())
    time.sleep(5)

if __name__ == '__main__':
    pool = multiprocessing.Pool(5) #创建了5个进程
    for i in range(20):
        pool.apply_async(func=work,args=(i,))

    time.sleep(20)
0 ,进程id: 8900
1 ,进程id: 15076
2 ,进程id: 11272
3 ,进程id: 17004
4 ,进程id: 15444

5 ,进程id: 15076
6 ,进程id: 8900
7 ,进程id: 11272
8 ,进程id: 17004
9 ,进程id: 15444

10 ,进程id: 15076
11 ,进程id: 8900
12 ,进程id: 11272
13 ,进程id: 17004
14 ,进程id: 15444

15 ,进程id: 8900
16 ,进程id: 15076
17 ,进程id: 17004
18 ,进程id: 11272
19 ,进程id: 15444

 运行结果,可以看出:

1.进程id 是重复利用的,说明所有的进程是创建好的,放在一个Pool中。

2.因为Pool中一开始创建了5个进程,所以可以看到每次输出,都以5个,5个一起输出,因为Pool的最大能力是5。可以看到进程id 不是按照递增的顺序进行的,因为Pool 创建进程是异步的。

3.可以看到在主进程中有这一行代码:time.sleep(20),如果没有加这行代码,就看不到任何输出,为什么会这样呢?因为,在我们进程池还没有创建成功时,主进程已经运行完了。

4.如果不采用 time.sleep(20) 这种延时操作的话,也可以在后面加入 pool.close() pool.join() 来阻塞,这样也会等到进程池全部创建完毕。代码如下:

#coding:utf-8

import time
import os
import multiprocessing

def work(count):
    print(count,',进程id:',os.getpid())
    time.sleep(5)

if __name__ == '__main__':
    pool = multiprocessing.Pool(5) #创建了5个进程
    for i in range(20):
        pool.apply_async(func=work,args=(i,))

    pool.close()
    pool.join()

获取进程的返回值:

#coding:utf-8

import time
import os
import multiprocessing

def work(count):
    print(count,',进程id:',os.getpid())
    time.sleep(5)
    return 'result is %d,pid is %d' % (count,os.getpid())

if __name__ == '__main__':
    pool = multiprocessing.Pool(5) #创建了5个进程
    results=[]
    for i in range(20):
        result=pool.apply_async(func=work,args=(i,))
        results.append(result)

    for res in results:
        print(res.get())  # 通过这种方式,也就不需要后续调用 pool.close() 和 pool.join()

    # pool.close()
    # pool.join()

进程锁 :

#coding:utf-8

import time
import os
import multiprocessing

def work(count,lock):
    lock.acquire()
    print(count,',进程id:',os.getpid())
    time.sleep(5)
    lock.release()
    return 'result is %d,pid is %d' % (count,os.getpid())

if __name__ == '__main__':
    pool = multiprocessing.Pool(5) #创建了5个进程
    manager = multiprocessing.Manager()
    lock=manager.Lock()
    #results=[]
    for i in range(20):
        result=pool.apply_async(func=work,args=(i,lock))
        #results.append(result)

    # for res in results:
    #     print(res.get())  # 通过这种方式,也就不需要后续调用 pool.close() 和 pool.join()

    pool.close()
    pool.join()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

repinkply

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值