Sunday 20 December 2015

Python: multiprocessing: synchronizing communication between processes

‘multiprocessing.Lock’ class is used for serializing the execution of processes.

Lock class provide following methods.
Method
Description
acquire(self, blocking=True, timeout=-1)
'acquire' method is used to acquire a lock. Returns True if the lock is acquired successfully, False if not. If this method is invoked with the blocking argument set to True, block until the lock is unlocked, then set it to locked and return True. When invoked with the blocking argument set to False, do not block.

You can set the maximum timeout by setting timeout value. It is a floating-point number, specifies the maximum number of seconds that this thread can block.  A timeout argument of -1 specifies an unbounded wait.
release()
Release a lock. This can be called from any thread, not only the thread which has acquired the lock. If you call this method on an unlocked lock, a RuntimeError is raised.


from multiprocessing import Process, Lock
import time

def processData(lock, task):
    print(task, ": Trying to acquire lock")
    lock.acquire()
    print(task, " Lock acquired")
    print(task, ": processing data")

    time.sleep(3)
    print(task, " : Releasing lock")
    lock.release()
    print(task, " : Released lock")

if __name__=="__main__":
    myLock=Lock()

    task1="task1"
    task2="task2"

    process1=Process(target=processData, args=(myLock,task1))
    process2=Process(target=processData, args=(myLock,task2))

    process1.start()
    process2.start()


Sample Output
task1 : Trying to acquire lock
task1  Lock acquired
task1 : processing data
task2 : Trying to acquire lock
task1  : Releasing lock
task1  : Released lock
task2  Lock acquired
task2 : processing data
task2  : Releasing lock
task2  : Released lock




Previous                                                 Next                                                 Home

No comments:

Post a Comment