threads/150889: PTHREAD_MUTEX_INITIALIZER + pthread_mutex_destroy() == EINVAL

Christopher Faylor cgf at netapp.com
Thu Sep 23 20:10:02 UTC 2010


On Thu, 2010-09-23 at 14:14 -0400, John Baldwin wrote:
> I suppose that is true, but I think this is also probably buggy code if you
> are doing this.  The use case for PTHREAD_MUTEX_INITALIZER is static
> initialization of static objects to ease adding locking to C libraries where
> constructors are not easy.  Specifically, to avoid prefixing every
> pthread_mutex_lock() with a pthread_once() call to initialize the mutex.
> (See the example given in the RATIONALE section in the pthread_mutex_init()
> page at the link above where it talks about static initialization.)  Such
> mutexes are generally never destroyed (their lifetime is the same as the
> containing executable or shared library (since presumably they could vanish
> as part of a dlclose())).  I think it is not provided so that you can
> initialize dynamically allocated mutexes at runtime via:
> 
> 	struct foo {
> 		...
> 		pthread_mutex_t m;
> 	}
> 
> 	f = malloc(sizeof(foo);
> 	f->m = PTHREAD_MUTEX_INITIALIZER;
> 
> Those sorts of locks should be initialized via pthread_mutex_init() instead.
>...
> 
> The one possibly valid reason I can see for pthread_mutex_destroy() to
> operate on a statically initialized mutex is to let a library destroy a
> mutex due to dlclose() unloading the library.  However, to pull that off the
> library would need to install an atexit() hook or similar to actually invoke
> pthread_mutex_destroy().  That requires some sort of initialization code to
> invoke atexit() at which point you might as well call pthread_mutex_init()
> to initialize the mutex at the same time as calling atexit().

I don't see how this represents buggy code.  It should be possible to
destroy a mutex which is allocated statically.  Currently, if a mutex is
assigned to PTHREAD_MUTEX_INITIALIZER and then used once, it can be
successfully destroyed.  It is only receive an EINVAL when there has
been no intervening call to any mutex function.  I don't think that a
PTHREAD_MUTEX_INITIALIZER using program should have to check for that.

However, regardless, this is still a bug in pthread_mutex_destroy right?


More information about the freebsd-threads mailing list