will parent process and child process in deadlock if parent is using resource and child will also get same resource ? what if parent contains two threads ? will child also get 2 threads ? how can fork will be thread safe ?
The one sentence description from Wikipedia is
A deadlock is a situation wherein two or more competing actions are each waiting for the other to finish, and thus neither ever does.
The simplest case is two threads and two resources.
Thread A:
acquireResource(r1)
acquireResource(r2)
// Do stuff
releaseResource(r1)
releaseResource(r2)
Thread B:
acquireResrouce(r2)
acquireResource(r1)
// Do stuff
releaseResource(r1)
releaseResource(r2)
With this code deadlock occurs if the following sequence of events occurs.
- Thread A acquires r1
- Context switch to thread B
- Thread B acquires r2
At that point Thread A can't proceed because it r2 is already owned and thread B can't proceed because r1 is owned. Therefore neither thread can proceed to the point where they release their resources. This is a deadlock.
For what its worth simple cases like this can be avoided by ensuring that resources are acquired in the same order throughout the code. For example, if thread B acquired r1 first no deadlock would arise. There are plenty of other ways of achieving deadlock though that are significantly harder to avoid.