【问题标题】:C Confused on how to initialize and implement a pthread mutex and condition variableC 对如何初始化和实现 pthread 互斥锁和条件变量感到困惑
【发布时间】:2014-06-17 11:35:03
【问题描述】:

我对如何初始化和实现 pthread 互斥锁和条件变量有点困惑。该程序的目标是让生产者将一定数量的整数放入队列中,而消费者将整数从队列中取出。我还必须能够定义创建的生产者和消费者线程的数量。在起始代码中,我给出了这些:

// 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);

?

我的代码现在有很多错误,所以我想至少在进一步调试之前确保我正确使用了互斥锁和条件。提前致谢!

【问题讨论】:

  • 你的问题到底是什么?
  • 互斥体我很确定你已经掌握了,但是对于这些条件变量,cmets 中的白话看起来像一个问题。条件变量不“指示”任何东西。它们是一种信号机制。该机制在与互斥体结合使用时,会发出拥有的外部谓词数据的状态变化信号。
  • 哦,不要用PHREAD_MUTEX_INIT初始化条件变量。这显然是错误的。使用PTHREAD_COND_INITIALIZER
  • 我的问题是我是否正确地实现了这些。我的代码有问题,我正在尝试查看我是否至少正确初始化并调用了这些代码。
  • 感谢 WhozCraig,我将它们用作信号机制。我只是认为教授的评论措辞不正确。

标签: c pthreads conditional-statements mutex producer-consumer


【解决方案1】:

如果您想使用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);

要检查条件变量,您必须使用循环以避免虚假解除阻塞,并且必须在以下情况下锁定互斥锁:

  • 检查条件
  • 更改指示当前状况的状态
  • 致电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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-19
    • 2020-08-07
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多