进程间同步,可以使用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

  

  

  

  

相关文章:

  • 2022-12-23
  • 2021-05-31
  • 2022-12-23
  • 2021-04-17
  • 2021-08-08
  • 2021-09-28
  • 2022-03-07
  • 2021-07-20
猜你喜欢
  • 2021-08-11
  • 2021-04-12
  • 2022-12-23
  • 2021-06-21
  • 2021-07-23
  • 2022-01-14
相关资源
相似解决方案