1

Related to this question --- I'm debugging some code that unlocks a mutex twice and I'm trying to figure out exactly when it happens. I'm getting stack traces out of Helgrind, but I'd like the program to crash immediately when it performs the bad unlock.

I know the behavior of unlocking an already-unlocked mutex is undefined, and so nasal demons are an acceptable implementation --- I certainly can't force nasal demons to crash. But given the pthreads implementation in recent versions of glibc, is there a way to get this behavior reasonably reliably?

Community
  • 1
  • 1
Patrick Collins
  • 10,306
  • 5
  • 30
  • 69
  • 1
    Setting the mutex type to `PTHREAD_MUTEX_ERRORCHECK` will cause an unlock to fail if the mutex is already unlocked. Obviously that doesn't automatically cause a crash and would rely on your calling code detecting an unlock failure. So it may or may not help you but pointing out in case it does. – kaylum Jan 12 '16 at 01:13

1 Answers1

3

Instead of obtaining a crash, what you can do is check the return value of pthread_mutex_unlock, and use an error-checking mutex (PTHREAD_MUTEX_ERRORCHECK mutex type). If you detect an error, call abort() or whatever.

Kaz
  • 55,781
  • 9
  • 100
  • 149
  • Great, I couldn't find this in the docs. Is it set with a pthread_mutex_attr_t? For the sake of completeness, could you point me towards docs or a relevant snippet? – Patrick Collins Jan 12 '16 at 01:17
  • @PatrickCollins: The POSIX docs for [`pthread_mutex_unlock()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_unlock.html) and [`pthread_mutexattr_settype()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutexattr_gettype.html) have the relevant information. – caf Jan 12 '16 at 03:02