Synchronization issue using Python's multiprocessing module

我怕爱的太早我们不能终老 提交于 2019-12-23 00:52:27

问题


When I run the following code in from Python's multiprocessing module page:

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

Sometimes I get unordered output such as:

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

Note that 4 is printed before 3 and 6 is printed before 5. Why?


回答1:


Because the whole point of multiprocessing is parallelism. Your processes are running at the same time as each other, so they may actually start and finish in any order.

The lock acquisition only ensures that they don't try to print at the same time - but that lock may be acquired by the various processes in any random order. It's more likely to be acquired by the first process you create, because that process will go through its initialization sooner and thus likely be the first one to request the lock. But there's no guaranteed of the order.




回答2:


It depends on how the OS schedules which one runs first, and your lock only prevents more than one of them running at the same time.



来源:https://stackoverflow.com/questions/15121859/synchronization-issue-using-pythons-multiprocessing-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!