UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2009-09-19 01:46 PM

Tommo
Member
Registered: 2007-09-03
Posts: 76

Re: Mutex deadlock

Hi. I'm a little confused about this.  I don't understand why a thread would try and lock the same mutex twice in a row.  When would this ever occur?  You lock, you do what needs doing, then you unlock.

Offline

#2 2009-09-20 06:10 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,234

Re: Mutex deadlock

Tread A locks X and then tries to take Y.

Thread B locks Y and then tries to take X.

Result: Deadlock.

Deadlocks can always happen when a thread takes more than one lock and
not all threads take all locks in the same order (no global lock ordering).

Offline

#3 2009-09-20 07:42 PM

Tommo
Member
Registered: 2007-09-03
Posts: 76

Re: Mutex deadlock

Thanks i3839.  Yeah that makes sense, I misinterpreted what the tutorial was saying.

Offline

#4 2009-09-21 11:14 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: Mutex deadlock

There are some mutex types where if a thread already has the mutex locked, and tries to lock it a second time, the thread will deadlock with itself.  Those mutex types are used for best (i.e. slightly better) performance, but of course you have to be very careful when using them not to trip over your own feet.

The smarter kind of mutex (that keeps track of whether the locking thread has already locked the mutex, and if so, just increments a counter instead of putting the thread to sleep) is called a recursive mutex, and is less tricky to use.

(btw:  as for why a thread would want to lock a mutex more than once... imagine a function that needs to serialize access to some data, but can be called both from contexts where the mutex is already locked, and contexts where it isn't locked.  The easiest way to implement that function is to just always lock the mutex, even if it already is locked.  The other way would be to check if the mutex is not locked, and if it isn't, lock it, but that's more complex and might expose you to a race condition if the mutex's locked-state changes after you do the is-locked check, but before you lock it)

Offline

#5 2009-09-22 04:02 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,234

Re: Mutex deadlock

You didn't misinterpret the tutor, like Jeremy made clear. There is just
more than one way to get a deadlock, and a single thread locking the
same mutex twice is the simplest case.

Offline

Board footer

Powered by FluxBB