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

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


The following reply was made to PR threads/150889; it has been noted by GNATS.

From: Christopher Faylor <cgf at netapp.com>
To: freebsd-threads at freebsd.org, freebsd-gnats-submit at freebsd.org
Cc:  
Subject: Re: threads/150889: PTHREAD_MUTEX_INITIALIZER +
 pthread_mutex_destroy() == EINVAL
Date: Thu, 23 Sep 2010 15:41:51 -0400

 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 y=
 ou
 > are doing this.  The use case for PTHREAD_MUTEX_INITALIZER is static
 > initialization of static objects to ease adding locking to C libraries wh=
 ere
 > 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 vani=
 sh
 > as part of a dlclose())).  I think it is not provided so that you can
 > initialize dynamically allocated mutexes at runtime via:
 >=20
 > 	struct foo {
 > 		...
 > 		pthread_mutex_t m;
 > 	}
 >=20
 > 	f =3D malloc(sizeof(foo);
 > 	f->m =3D PTHREAD_MUTEX_INITIALIZER;
 >=20
 > Those sorts of locks should be initialized via pthread_mutex_init() inste=
 ad.
 >...
 >=20
 > 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 inv=
 oke
 > 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