Reputation: 434
A function is doing things on variables that must be protected against concurrent threads by a mutex.
The caller of this function locks a mutex, performs other things and calls this function.
Now a situation arised that requires this function to be called from another piece of code.
Of course this code could lock the mutex too but I thought perhaps the function could see if it must lock the mutex or not.
What I would need is a function that tells me if the current thread has locked the mutex. Then the function could go on without locking. Otherwise it would lock.
int need_to_lock = !my_thread_has_locked_the_mutex(&mutex);
if (need_to_lock)
mutex_lock(&mutex);
access variables;
if (need_to_lock)
mutex_unlock(&mutex);
Does my_thread_has_locked_the_mutex exist? I couldn't find anything.
I didn't know about recursive mutexes. They seem to do what I thought of.
What I use now is a not recursive mutex that blocks if locked twice from the same thread.
Upvotes: 2
Views: 205
Reputation: 179392
Why not just use a recursive mutex instead? A recursive mutex is substantially similar to a regular mutex, but can be locked multiple times by a single thread (i.e. recursively).
In some libraries, mutexes are recursive by default. With C pthreads, you need to opt in to recursive mutexes by initializing your mutexes appropriately:
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(mutex, &attr);
Another approach is to split your function into two variants: one that should be called with the mutex held, and one that should be called without the mutex held. The usual naming convention is to append _locked
to the former, or _unlocked
to the latter. The unlocked function simply locks the mutex and then calls the locked function, so there won’t be any real duplication of code here.
Upvotes: 3