使用Python的多处理模块的同步问题 [英] Synchronization issue using Python's multiprocessing module

查看:95
本文介绍了使用Python的多处理模块的同步问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从Python的多处理模块页面中运行以下代码时:

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

请注意,在3之前先打印4,在5之前先打印6.为什么?

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

推荐答案

因为multiprocessing的全部要点是 parallelism .您的进程彼此同时运行,因此它们实际上可以按任何顺序启动和结束.

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.

获取锁只能确保他们不会同时尝试print -但该锁可能由各种进程以任意随机顺序获取.您创建的第一个进程更有可能获得 ,因为该进程将更快地进行初始化,因此可能是第一个请求锁定的进程.但是不能保证顺序.

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.

这篇关于使用Python的多处理模块的同步问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆