On Wed, Oct 26, 2016 at 11:35:58AM +0200, Simon Ruderich wrote:

> >  static pthread_mutex_t attr_mutex;
> > -#define attr_lock()pthread_mutex_lock(&attr_mutex)
> > +static inline void attr_lock(void)
> > +{
> > +   static int initialized;
> > +
> > +   if (!initialized) {
> > +           pthread_mutex_init(&attr_mutex, NULL);
> > +           initialized = 1;
> > +   }
> > +   pthread_mutex_lock(&attr_mutex);
> > +}
> 
> This may initialize the mutex multiple times during the first
> lock (which may happen in parallel).
> 
> pthread provides static initializers. To quote the man page:
> 
>     Variables of type pthread_mutex_t can also be initialized
>     statically, using the constants PTHREAD_MUTEX_INITIALIZER
>     (for fast mutexes), PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
>     (for recursive mutexes), and
>     PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP (for error checking
>     mutexes).

I seem to recall this does not work on Windows, where the pthread
functions are thin wrappers over CRITICAL_SECTION. Other threaded code
in git does an explicit setup step before entering threaded sections.
E.g., see start_threads() in builtin/grep.c.

-Peff

Reply via email to