Does pthreads support any method that allows you to query the number of times a recursive mutex has been locked?
Asked
Active
Viewed 2,427 times
2 Answers
5
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.

Left For Archive
- 2,626
- 1
- 18
- 19
-
2Although you'd have to watch out for race conditions when writing the wrapper, which you wouldn't have to if pthreads supported this natively. – Andy Krouwel Nov 10 '15 at 09:31
1
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;

salsaman
- 956
- 6
- 3
-
a `counting_mutex` doesn't make a lot of sense. You want a separate count per each mutex (a single count shared by multiple mutexes isn't useful) in which case you don't need another mutex to protect the count, you can just protect it by using the same mutex – increment the count after lock and decrement before unlock, and hence you only ever modify it while holding the mutex. – Simon Kissane Jul 06 '23 at 23:21