This article focusses on dealing how to get more than one lock at a time if a multithread program is given along with avoiding the deadlocks.
Multithread programs – Due to the threads that keep on attempting to get multiple locks at once, these are very much prone to deadlocks. Understanding it with an example – a lock is already been acquired by a thread and then a second lock is attempted by the block then in that case, the program can freeze as the thread can potentially block the progress of other threads.
- Enforcement of ordering rule
- Assigning each lock in a unique manner to the program.
- Only allowing multiple locks to be acquired in ascending order.
Code #1 : Implementing the solution uisng a context manager.
Locks are acquired in the normal way using the context manager and for performing this task
acquire() function is used as there was more than one lock as shown in the code below :
Code #2 :
- Even after the acquisition of the locks specification in a different order in each function – the program will run forever without deadlock.
- Sorting the locks plays an important role according to the object identifier as locks after being sorted get acquired in a consistent manner regardless of how the user might have provided them to acquire().
- If multiple threads are nested as shown in the code below, to solve a subtle problem with detection potential deadlock, thread-local storage is used.
Code #3 :
On running this version of the program, one of the threads will crash with an exception such as :
Exception in thread Thread-1: Traceback (most recent call last): File "/usr/HP/lib/python3.3/threading.py", line 639, in _bootstrap_inner self.run() File "/usr/HP/lib/python3.3/threading.py", line 596, in run self._target(*self._args, **self._kwargs) File "deadlock.py", line 49, in thread_1 with acquire(y_lock): File "/usr/HP/lib/python3.3/contextlib.py", line 48, in __enter__ return next(self.gen) File "deadlock.py", line 17, in acquire raise RuntimeError("Lock Order Violation") RuntimeError: Lock Order Violation
Each thread remembers the lock been already acquired that’s why it’s been showing this error. The ordering constraints that acquired the locks is also enforced and list of previously acquired locks is checked by the
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.