C Confused on how to initialize and implement a pthread mutex and condition variable

帅比萌擦擦* 提交于 2019-12-03 21:43:34

If you want to use the PTHREAD_XXX_INITIALIZER macros you should use them in the variable declaration. Also use PTHREAD_COND_INITIALIZER for condition variables:

// Locks & Condition Variables
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // Lock shared resources among theads
pthread_cond_t full  = PTHREAD_COND_INITIALIZER;  // Condition indicating queue is full
pthread_cond_t empty = PTHREAD_COND_INITIALIZER; // Condition indicating queue is empty

Don't use those macros to initialize the mutex or condition variable later. If you need to do it later (for example if the object is dynamically allocated), use the appropriate init function:

pthread_mutex_init( &lock, NULL);
pthread_cond_init( &full, NULL);
pthread_cond_init( &empty, NULL);

To check a condition variable you must use a loop in order to avoid spurious unblocks and you must lock the mutex when:

  • checking the condition
  • changing the state that indicates the current condition
  • calling pthread_cond_wait()

So whatever is waiting for an is-empty condition might look like:

pthread_mutex_lock(&lock);
while (!isEmpty) {
    pthread_cond_wait( &lock, &empty);
}

// isEmpty is non-zero and the lock is held

Whatever is signalling that something is-empty might look like:

pthread_mutex_lock(&lock);

// ...
// we have emptied the queue while holding the lock

isEmpty = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&empty);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!