Does pthreads support a method for querying the "lock count" of a recursive mutex?

2.5k views Asked by At

Does pthreads support any method that allows you to query the number of times a recursive mutex has been locked?

2

There are 2 answers

1
Left For Archive On BEST ANSWER

There is no official, portable way to do this.

You could get this behavior portably by tracking the lock count yourself—perhaps by writing wrappers for the lock and unlock functions, and creating a struct with the mutex and count as members.

1
salsaman On

You can do it using a second mutex, e.g. counting_mutex.

Then instead of pthread_mutex_lock:

pthread_mutex_lock(&counting_mutex);
pthread_mutex_lock(&my_mutex);
pthread_mutex_unlock(&counting_mutex);

instead of pthread_mutex_unlock:

pthread_mutex_lock(&counting_mutex);
pthread_mutex_unlock(&my_mutex);
pthread_mutex_unlock(&counting_mutex);

then you can add pthread_mutex_count:

int count = 0, i = 0;
pthread_mutex_lock(&counting_mutex);
while (!pthread_mutex_unlock(&my_mutex)) count++;
while (i++ < count) pthread_mutex_lock(&my_mutex);
pthread_mutex_unlock(&counting_mutex);
return count;