Suppose I have a system with N processes. Each process needs max K resources (K << N). To prevent collisions a process needs to lock each resource before accessing it. Is a deadlock possible and if yes, what is the maximum N for which the system is still deadlock free?
2 Answers
The maximum N is 1. with 2 or more threads interacting in the same process with the same memory, a deadlock is entirely possible. Scenario:
A asks for and receives lock 1
B asks for and receives lock 2
A asks for lock 2 and pauses
B asks for lock 1 and pauses
A and B now deadlock
The order of locking must be consistent for > 1 locks in order to fully prevent deadlocks.

- 32,775
- 8
- 59
- 68
'To prevent collisions a process needs to lock each resource before accessing it' - this is misleading/incorrect. It needs to lock EVERY resource it needs in one 'lock' operation or remain blocked until that entire set becomes available. It is quite possible for a threads to submit a resource requirement set to a resource management struct/instance and to remain blocked until ALL the resources in the set become available without preventing access to any of them while waiting.
Applying a lock to each resource and having threads try to serially lock up the resources is a naive solution that will likely fail for any N>1, as explained by Haney.

- 24,453
- 3
- 36
- 60