Junior — Middle
How can mutual process blocking be avoided or eliminated in a system?
sobes.tech AI
Answer from AI
Mutual exclusion (deadlock) occurs when two or more processes are permanently waiting for resources held by each other. To avoid or eliminate deadlock, the following approaches are used:
- Avoid cyclic dependencies: always request resources in the same order to prevent waiting cycles.
- Use timeouts: attempt to acquire a resource with a timeout to avoid waiting indefinitely, and release already acquired resources if unsuccessful.
- Avoid hold and wait: processes should request all necessary resources at once or release already held resources if they cannot obtain all at once.
- Apply detection and recovery algorithms: periodically check the system for deadlock and, upon detection, interrupt or roll back one of the processes.
In Java, for example, you can use tryLock with a timeout from java.util.concurrent.locks.Lock to prevent mutual locking:
Lock lock1 = new ReentrantLock();
Lock lock2 = new ReentrantLock();
if(lock1.tryLock(1000, TimeUnit.MILLISECONDS)) {
try {
if(lock2.tryLock(1000, TimeUnit.MILLISECONDS)) {
try {
// critical section
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}
This approach helps avoid infinite waiting and deadlock.