python Synchronization between processes

进程间同步,可以使用lock进行控制。

官方文档的例子如下:

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

运行结果:

1
2
3
4
5
6
7
8
9
10
hello world 0
hello world 1
hello world 2
hello world 3
hello world 4
hello world 5
hello world 6
hello world 7
hello world 8
hello world 9

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from multiprocessing import Process, Lock
from time import sleep
 
def f(l, i):
    l.acquire()
    print 'hello world', i
    l.release()
 
def n(l,i):
    l.acquire()
    print 'hello world', i
    sleep(5)
    l.release()
 
if __name__ == '__main__':
    lock = Lock()
    result = []
 
    result.append(Process(target = n,args = (lock,'first')))
    result.append(Process(target = f,args = (lock,'sec')))
 
    for x in result:
        x.start()
 
    for x in result:
        x.join()
 
    print('main process run OK')

运行结果:

1
2
3
4
hello world first
中间等待5秒钟
hello world sec
main process run OK

  

  

  

  

posted @   “人生苦短”  阅读(359)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示