pshared: Improve mutex_init_pshared_with_type()
authorBart Van Assche <bvanassche@acm.org>
Sat, 30 May 2020 23:03:48 +0000 (16:03 -0700)
committerBart Van Assche <bvanassche@acm.org>
Wed, 10 Jun 2020 02:28:06 +0000 (19:28 -0700)
Skipping the pthread_mutexattr_settype() call if type == 0 is questionable
because it makes it impossible to initialize a mutex with type == 0 (type 0
corresponds to PTHREAD_MUTEX_TIMED_NP on Linux). Use symbolic names for
pthread mutex types and leave out the type == 0 check.

Fixes: 3ed6894b00c4 ("pshared: Add mutex_init_pshared_with_type()")
Signed-off-by: Bart Van Assche <bvanassche@acm.org>
pshared.c

index e671c87f86bf4f7601192f4ea5b1887d1ad13f12..182a36529df70acbd9b254a00444c2eacc02c2c6 100644 (file)
--- a/pshared.c
+++ b/pshared.c
@@ -39,6 +39,10 @@ int cond_init_pshared(pthread_cond_t *cond)
        return 0;
 }
 
+/*
+ * 'type' must be a mutex type, e.g. PTHREAD_MUTEX_NORMAL,
+ * PTHREAD_MUTEX_ERRORCHECK, PTHREAD_MUTEX_RECURSIVE or PTHREAD_MUTEX_DEFAULT.
+ */
 int mutex_init_pshared_with_type(pthread_mutex_t *mutex, int type)
 {
        pthread_mutexattr_t mattr;
@@ -60,26 +64,24 @@ int mutex_init_pshared_with_type(pthread_mutex_t *mutex, int type)
                return ret;
        }
 #endif
-       if (type) {
-               ret = pthread_mutexattr_settype(&mattr, type);
-               if (ret) {
-                       log_err("pthread_mutexattr_settype: %s\n",
-                               strerror(ret));
-                       return ret;
-               }
+       ret = pthread_mutexattr_settype(&mattr, type);
+       if (ret) {
+               log_err("pthread_mutexattr_settype: %s\n", strerror(ret));
+               return ret;
        }
        ret = pthread_mutex_init(mutex, &mattr);
        if (ret) {
                log_err("pthread_mutex_init: %s\n", strerror(ret));
                return ret;
        }
+       pthread_mutexattr_destroy(&mattr);
 
        return 0;
 }
 
 int mutex_init_pshared(pthread_mutex_t *mutex)
 {
-       return mutex_init_pshared_with_type(mutex, 0);
+       return mutex_init_pshared_with_type(mutex, PTHREAD_MUTEX_DEFAULT);
 }
 
 int mutex_cond_init_pshared(pthread_mutex_t *mutex, pthread_cond_t *cond)