Domanda

Is there a foolproof way to automatically release mutexes held by a thread when that thread is exiting (in its destructor)?

The approach I have been taking is to create a structure for each mutex which hold the identity of the thread that holds it, and then in the destructor to scan through this list and if any mutexes match the thread being finished, to release it then. But I'm thinking that this actually has a race condition: what happens if after I lock the mutex but before I set the data structure the destructor is called?

I've also looked at pthread_mutexattr_setrobust_np, but my understanding is that np functions are non-portable, and I have had issues with that in the past.

For reference, each thread is associated with a TCP/IP connection, and locking/unlocking occurs in response to requests over this connection. If the connection abnormally closes I need to clean up i.e. release any locks held.

È stato utile?

Soluzione

I found a solution which appears to work. First, I use an error checking mutex (PTHREAD_ERRORCHECK_MUTEX_INITIALIZER or PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP).

Next, in the destructor, I trying to unlock all mutexes, with the idea being any mutex not owned by the thread will be left alone, but any mutex owned by the thread will be released.

For some reason even mutexes owned by the thread return EPERM, but a subsequent attempt to re-lock the mutex from another thread succeeds whereas without trying to unlock another attempt will deadlock. Conversely, other mutexes not owned by the destructed thread are still found to be locked after the destructor runs.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top