blueshift
blueshift

Reputation: 6882

Possible to check mutex is locked before calling pthread_cond_wait()?

I'd like to add some debugging code to an abstraction of pthread_cond_wait in my code to check that the calling code really holds the mutex, as it should. This is to check correctness of the rest of the callers.

Is there a way to check if the mutex is locked, or enable a debug mode in the pthreads implementation (on Linux) to tell me if it's not?

Upvotes: 2

Views: 5203

Answers (3)

blueshift
blueshift

Reputation: 6882

The answer, pieced together from zvrba and "R" and some other research, is to create the mutexes with error-checking attributes and check the return value of pthread_cond_wait().

pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_ERRORCHECK);

Other relevant info:

  • My glibc requires #define _GNU_SOURCE before any includes to enable pthread_mutexattr_settype()

  • I found I do have the POSIX manpages installed as well as the "LinuxThreads" ones. I'm not sure what (ubuntu) packages the various ones came from, but editing /etc/manpath.config to put "3posix" first means I get the right ones now.

Upvotes: 0

caf
caf

Reputation: 239011

If you create the mutex as an error-checking mutex, using:

pthread_mutexattr_t attr;
pthread_mutex_t errchkmutex;

pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_init(&errchkmutex, &attr);

...then pthread_cond_wait() will return EPERM if the mutex is not locked by the calling thread.

(of course you would add error-checking to that mutex initialisation code).

I think error-checking mutexes are exactly the kind of "debugging mode" that you're looking for.

Upvotes: 3

zvrba
zvrba

Reputation: 24546

pthread_cond_wait will fail unless the mutex is locked by the calling thread. Are you checking return values of pthread functions? If not, this is a recipe for disaster, moreso with threading than with other system calls.

Upvotes: 0

Related Questions