Question

I know it's kind of "breaking the rules", but I'm looking for an option to force unlock a mutex, possibly from a different thread.

It may be considered as some kind of hacking, since it's probably not really supported by the conventional API, but is there an option like that?

One scenario that may be interesting for me is for example, in case there's a need for a cleanup, and one thread performs general cleanup, but a different thread is working on a mutex that it locked, and it's not a real option to wait for that thread to release it.

I'm using pthread mutexes.

Was it helpful?

Solution

You can destroy the mutex using pthread_mutex_destroy(pthread_mutex_t *mutex). The waiting (lock or trylock) will return with EINVAL which you may interpret as a branch to your "cleanup". Note: The mutex object is not valid anymore after this operation. But there is some danger left since: Attempting to destroy a locked mutex results in undefined behavior. Undefined behaviour is this sense means that YOU have to take care about this special condition. But this was your intention, so just do your cleanup branch correct, only touch things which were protected by the mutex when sure that no other thread is doing so. Afterwards a destroyed mutex object can be reinitialized.

OTHER TIPS

If all you are interested in is 'cleaning up', use a semaphore for locking - you can always stuff in an extra unit to wake up a waiting thread in order to get it to terminate.

If the process is going to close, I don't bother with cleanups anyway, unless there is some important, overriding reasons to, (a 'clean' valgrind dump is not one of them:).

Is the problem here related to multiple threads waiting to acquire a particular mutex.

if the case is with a thread which is holding for a really long time. The following should help and will be cleaner. It will be preferred to make the code modular and check for conditions were you can bail out in the middle of the function which is holding the mutex.

By checking for the condition at multiple places you should be able to minimize the hold time and handle all the related cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top