[cfe-dev] libc++ mutex destructor assertion

Howard Hinnant howard.hinnant at gmail.com
Fri Jun 13 11:05:35 PDT 2014


On Jun 13, 2014, at 1:34 PM, Chandler Carruth <chandlerc at google.com> wrote:

> 
> On Fri, Jun 13, 2014 at 6:32 PM, David Majnemer <david.majnemer at gmail.com> wrote:
>> It is very reasonable for this to be UB.  Imagine a mutex where memory is allocated in pthread_mutex_init and free'd in pthread_mutex_destroy.  Unlocks which race with the destruction may end up partying on free'd memory.
>>  
>> 
>>> It's very easy to support this -- just don't call pthread_mutex_destroy(), the function has no purpose really.
>>> 
>> This is not true. Some implementations, like FreeBSD's libthr, free memory in their pthread_mutex_destroy.  Not calling pthread_mutex_destroy will lead to leaks.
>> 
> This ... makes me extremely sad. It makes mutexes significantly more annoying to use in a bunch of patterns if you cannot destroy them while locked.

Fwiw, I once wrote a mutex adaptor/wrapper where in its destructor it locked itself, and then did the necessary de-initialization, then put itself in a “destructed state” and unlocked itself.  When another thread comes along and tries to lock it after destruction, it recognizes the destructed state and throws an exception.  Not 100% bulletproof.  But when the mutex has static storage duration, can be fairly effective.

That being said, this particular wrapper would not be useful in Zachary’s example as the lock is leaked by the exiting thread.  However one can dream up all kinds of variations on custom mutexes, and they can all interoperate with std::lock_guard, std::unique_lock, std::condition_variable_any, std::lock, etc.

Howard





More information about the cfe-dev mailing list