views:

361

answers:

6

I was stuck at one question in an interview.

Given two threads, and each one has a lock, how to guarantee no deadlock.

My knowledge is that it is not easy to avoid deadlock, that's why I got stuck. Can anybody give a hint.

Thanks!

+11  A: 

The description is a bit lacking, but if you impose a locking order (e.g, if the locks are A and B, never lock B unless you already locked A, and never release A while B is locked), then deadlock won't occur.

Ofir
Or better still, design for fewer locks.
Andrew
+1 this is effectively what a lot of modern systems like Linux Kernel's lockdep do. They check to make sure that the locks are always used in the same order. If they aren't, then the system can deadline.
Broam
+1  A: 

With a single lock it's not possible to get deadlocked unless one refuses to release their lock -- in which case the waiting thread is called starved. For multiple locks, they must be released in the reverse order that they were acquired, and both threads must agree on the order.

What you are trying to avoid here is this situation:

A has lock 1 waiting on lock 2

B has lock 2 waiting on lock 1

Joel
a thread that refuses to release a lock does not trigger a deadlock. The thread in question is still running.
Bahbar
Bahbar, I believe Joel is saying that with a single lock, a thread that forget to release the lock can prevent another thread from ever making progress. You're right that this is technically not called deadlock, but it's probably still part of the things that the interviewer would care to prevent.
redtuna
A: 

A lot of work on concurrent/parallel programming is focused on lock-free designs. Not an exact answer to your question, but as Andrew already mentioned on this thread, the best way to avoid deadlocks is to not lock at all. A lot of very smart people working on concurrency issues are of that opinion.

Kevin Won
A: 

Lock ordering is preferable to timeouts/deadlock detection, but sometimes timeouts are necessary, particularly if you don't control all of the components in the system: hence deadlock timeout/detection in databases. If all of the callers were clever enough, deadlocks would never happen, but commonly not all of the callers are clever enough.

phlip
A: 

The answer your interviewers were going for is probably WaitForMultipleObjects(). That's a Windows API that locks both (or more) resources simultaneously.

Seva Alekseyev
+1  A: 

There are known deadlock avoidance algorithms that can detect if a deadlock is about to occur and avoid the system getting into that state. For example, the Banker's Algorithm.

Mike Daniels