简体   繁体   English

锁定多处理包不起作用

[英]Lock in multiprocessing package not working

The following code is very simple, only for testing purposes, but I am not getting the output as desired: 以下代码非常简单,仅用于测试目的,但我没有得到所需的输出:

from multiprocessing import Process,Lock

def printing(l,i):
    l.acquire()
    print i
    l.release()

if __name__ == '__main__':
    lock = Lock()

    for i in range(10):
        Process(target=printing,args=(lock,i)).start()

The output is: 输出是:

0
1
2
3
5
6
4
7
8
9

Locks are supposed to suspend the other processes from executing. 锁应该暂停其他进程的执行。 Why isn't it happening here? 为什么不在这里发生?

What output did you expect? 你期望什么输出? The output looks fine to me: a permutation of range(10) . 输出看起来很好: range(10)的排列range(10) The order in which the Processes happen to execute may vary from run to run. 进程执行的顺序可能因运行而异。 That's expected. 这是预期的。

I suspect you misunderstand what a lock does. 我怀疑你误解了锁的作用。 When you acquire a lock, then every other process also trying to acquire the same lock blocks until the lock is released. 当您获得锁定时,其他每个进程也会尝试获取相同的锁定块,直到锁定被释放。 That's all. 就这样。 In your test run, process 0 happened to acquire the lock first. 在测试运行中,进程0碰巧首先获得锁。 Any other processes also trying to acquire the lock are blocked until process 0 releases the lock. 在尝试获取锁定的任何其他进程都将被阻止,直到进程0释放锁定。 Process 0 prints 0 and then releases the lock. 进程0打印0然后释放锁。 Then it so happened that process 1 acquired the lock. 然后碰巧过程1获得了锁定。 Etc. 等等。

Comment out your l.release() , and you'll see that your program never finishes: the first process that happens to acquire the lock then prints its integer, and all other processes are forever blocked waiting to acquire the lock. 注释掉你的l.release() ,你会看到你的程序永远不会完成:获得锁的第一个进程然后打印它的整数,所有其他进程永远被阻塞等待获取锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM