Showing posts with label mutex. Show all posts
Showing posts with label mutex. Show all posts

Thursday, 7 April 2016

Deadlocks


What is a deadlock?

Deadlocks are the most common scenarios occuring in a multi-threaded environment. In computing/technical terms a deadlock can be a scenario where there are two or more parties waiting for a resource but neither of them can proceed.

How can a deadlock happen?

A deadlock situation can arise if and only if the following four conditions occur at the same time in the system -
  1. Mutual Exclusion: At least one resource is held in a non-sharable mode that is only one process at a time can use the resource. If another process requests that resource, the requesting process must be delayed until the resource has been released.
  2. Hold and Wait:There must exist a process that is holding at least one resource and is waiting to acquire additional resources that are currently being held by other processes. 
  3. No Preemption: Resouces cannot be preempted; that is, a resource can only be released voluntarily by the process holding it, after the process has completed its task. 
  4. Circular Wait: There must exist a set {p0, p1,.....pn} of waiting processes such that p0 is waiting for a resource which is held by p1, p1 is waiting for a resource which is held by p2,..., pn-1 is waiting for a resource which is held by pn and pn is waiting for a resource which is held by p0
Ways to prevent a deadlock - 
There can be many ways to prevent a deadlock -
  1. Semaphore.
  2. Monitors.
  3. Mutex variable.