码迷,mamicode.com
首页 > 编程语言 > 详细

python中的Lock

时间:2015-07-01 09:43:52      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

 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..

 

python中的Lock

标签:

原文地址:http://www.cnblogs.com/liunnis/p/4612298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!