python Synchronization between processes

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

官方文档的例子如下:

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()

运行结果:

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

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')

运行结果:

hello world first
中间等待5秒钟
hello world sec
main process run OK

  

  

  

  

原文地址:https://www.cnblogs.com/hester/p/4911072.html