Deadlock is a situation in which no members can act because they are each dependent (waiting) on each other.
Example: P1 requires resource R1 and is in possession of resource R2. P2 requires additional resource R2 and is in possession of R1; neither process can continue.
Deadlocks happen when two or more threads aren’t able to make any progress because the resource required by the first thread is held by the second and the resource required by the second thread is held by the first.
How to avoid deadlocks?
Avoid Nested Locks: This is the main reason for deadlock. Deadlock mainly happens when we give locks to multiple threads. Avoid giving locks to multiple threads if you already have given to one.
Avoid Unnecessary Locks: You should lock only those members which are required. Having unnecessary locks can lead to a deadlock. As a best practice, try to reduce the need to lock things as much as you can.