pthread_mutex_trylock() should never block

Daniel Eischen eischen at vigrid.com
Sat Dec 6 22:34:34 PST 2003


On Sun, 7 Dec 2003, Peter Kostouros wrote:

> I have been tracking mozilla (cvs) that terminates when linked against 
> libkse: basically a routine checks whether a mutex variable is locked 
> with a call to pthread_mutex_trylock() before it attempts to unlock it 
> with pthread_mutex_unlock(). The return value of pthread_mutex_trylock 
> is checked against EBUSY and terminates the process if it is otherwise. 
> In my particular scenario, pthread_mutex_trylock() returns EDEADLK: the 
> pthread_mutex_trylock man page does not mention EDEADLK as an error code.

The man page may not mention it, and that may be a bug, but I
think a pthread_mutex_trylock() on a non-recursive mutex is allowed
to return EDEADLK.

  http://www.opengroup.org/onlinepubs/007904975/functions/pthread_mutex_trylock.html

  If the mutex type is PTHREAD_MUTEX_ERRORCHECK, then error
  checking shall be provided. If a thread attempts to relock a
  mutex that it has already locked, an error shall be returned.
  If a thread attempts to unlock a mutex that it has not locked
  or a mutex which is unlocked, an error shall be returned.

  ...

  If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to
  recursively lock the mutex results in undefined behavior.
  Attempting to unlock the mutex if it was not locked by the
  calling thread results in undefined behavior. Attempting to
  unlock the mutex if it is not locked results in undefined
  behavior.

  The pthread_mutex_trylock() function shall be equivalent to
  pthread_mutex_lock(), except that if the mutex object
  referenced by mutex is currently locked (by any thread,
  including the current thread), the call shall return
  immediately. If the mutex type is PTHREAD_MUTEX_RECURSIVE and
  the mutex is currently owned by the calling thread, the mutex
  lock count shall be incremented by one and the
  pthread_mutex_trylock() function shall immediately return
  success.

> When the application is linked against libc_r or libthr, 
> pthread_mutex_trylock returns EBUSY in the scenario described above.
> 
> I suppose my question is how do you safely (and quickly) check the state 
> of a mutex variable?

I think you (the application) are supposed to remember whether a thread
has or has not locked a mutex.  By default, mutexes under FreeBSD are
error checking mutexes and will return EDEADLK when a thread attempts
pthread_mutex_trylock() on a mutex it already owns.

-- 
Dan Eischen



More information about the freebsd-threads mailing list