我对如何初始化和实现pthread互斥锁和条件变量有点困惑。该程序的目标是让生产者将一定数量的in放入队列中,而消费者将in从队列中取出。我还必须能够定义创建的生产者和消费者线程的数量。在起始代码中,我给出了以下代码:
// Locks & Condition Variables
pthread_mutex_t lock; // Lock shared resources among theads
pthread_cond_t full; // Condition indicating queue is full
pthread_cond_t empty; // Condition indicating queue is empty作为共享资源。在main方法的//TODO注释中,其中一个步骤是初始化锁和条件变量。我对pthread互斥锁和条件的理解非常薄弱,所以我要说:
lock = PTHREAD_MUTEX_INIT;
full = PTHREAD_MUTEX_INIT;
empty = PTHREAD_MUTEX_INIT;在消费者和生产者方法中,我是否可以这样调用锁:
pthread_mutex_lock(&lock);和
pthread_cond_wait(&full, &lock);我的代码现在有很多buggy,所以在进一步调试之前,我至少要确保我正确地使用了互斥量和条件。提前感谢!
发布于 2014-05-01 08:41:19
如果要使用PTHREAD_XXX_INITIALIZER宏,则应在变量声明中使用它们。也可以对条件变量使用PTHREAD_COND_INITIALIZER:
// 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以后不要使用这些宏来初始化互斥锁或条件变量。如果您需要稍后执行此操作(例如,如果对象是动态分配的),请使用适当的init函数:
pthread_mutex_init( &lock, NULL);
pthread_cond_init( &full, NULL);
pthread_cond_init( &empty, NULL);要检查条件变量,必须使用循环以避免虚假的解锁,并且在以下情况下必须锁定互斥:
检查condition
pthread_cond_wait()的状态的
因此,等待is-empty条件的内容可能如下所示:
pthread_mutex_lock(&lock);
while (!isEmpty) {
pthread_cond_wait(&empty, &lock);
}
// isEmpty is non-zero and the lock is held任何表示某物为空的信号可能如下所示:
pthread_mutex_lock(&lock);
// ...
// we have emptied the queue while holding the lock
isEmpty = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&empty);https://stackoverflow.com/questions/23400097
复制相似问题