Automatically releasing mutexes held when thread destructor runs
===

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.

