C: How do you declare a recursive mutex with POSIX threads?

后端 未结 4 1227
忘了有多久
忘了有多久 2020-12-07 17:47

I am a bit confused on how to declare a recursive mutex using pthread. What I try to do is have only one thread at a time be able to run a piece of code(including functions)

4条回答
  •  孤城傲影
    2020-12-07 18:14

    To create a recursive mutex, use:

    #include 
    int pthread_mutexatttr_settype(pthread_mutexattr_t *attr,
                                   int type);
    

    where type is PTHREAD_MUTEX_RECURSIVE.

    Don't forget to check the return value!

    Example:

    /* or PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP */
    pthread_mutex_t       mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutexattr_t   mta;
    

    or alternatively, initialize at runtime (don't do both, it's undefined behaviour):

    pthread_mutexattr_init(&mta);
    /* or PTHREAD_MUTEX_RECURSIVE_NP */
    pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE);
    
    pthread_mutex_init(&mutex, &mta);
    

提交回复
热议问题