python中的Lock

 1 #Lock.py
 2 from multiprocessing import Process,Lock
 3 import os
 4 
 5 def f(l,i):
 6     l.acquire()
 7     print('hello world %d and Ospid is %s...' %( i,os.getpid()))
 8     l.release()
 9 if __name__=='__main__':
10     lock = Lock()
11     for num in range(10):
12         Process(target=f,args=(lock,num)).start()

有Lock。

结果

 1 hello world 3 and Ospid is 4852...
 2 hello world 2 and Ospid is 540...
 3 hello world 0 and Ospid is 4160...
 4 hello world 1 and Ospid is 948...
 5 hello world 4 and Ospid is 5272...
 6 hello world 6 and Ospid is 3100...
 7 hello world 7 and Ospid is 3364...
 8 hello world 8 and Ospid is 924...
 9 hello world 9 and Ospid is 5196...
10 hello world 5 and Ospid is 5460...

以下是无Lock

 1 #copy.py
 2 __author__ = 'liunnis'
 3 from multiprocessing import Process,Lock
 4 import os
 5 
 6 def f(l,i):
 7 
 8     print('hello world %d and Ospid is %s...' %( i,os.getpid()))
 9 
10 if __name__=='__main__':
11     lock = Lock()
12     for num in range(10):
13        p = Process(target=f,args=(lock,num))
14        p.start()
15 #       p.join()

结果:

 1 hello world 3 and Ospid is 944...
 2 hello world 1 and Ospid is 4156...
 3 hello world 8 and Ospid is 2136...
 4 hello world 5 and Ospid is 3764...
 5 hello world 6 and Ospid is 4876...
 6 hello world 7 and Ospid is 4976...
 7 hello world 2 and Ospid is 2640...
 8 hello world 0 and Ospid is 1404...
 9 hello world 9 and Ospid is 5748...
10 hello world 4 and Ospid is 4032..

 

转载于:https://www.cnblogs.com/liunnis/p/4612298.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值