Reputation: 55
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?
Upvotes: 2
Views: 964
Reputation: 70582
What output did you expect? The output looks fine to me: a permutation of 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. Any other processes also trying to acquire the lock are blocked until process 0 releases the lock. Process 0 prints 0
and then releases the lock. Then it so happened that process 1 acquired the lock. 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.
Upvotes: 4