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

 

posted @ 2015-07-01 08:55  何似王  阅读(1569)  评论(0编辑  收藏  举报