问题
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