【问题标题】:C pthread_cond_broadcast seems to be broadcasting to all cond variablesC pthread_cond_broadcast 似乎正在向所有 cond 变量广播
【发布时间】:2013-02-26 04:44:39
【问题描述】:

我有一个结构数组。每个结构如下。

struct thread_st
{
    pthread_t thr;

    int conn;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
};

conn 指示线程是否有工作要做。如果它> = 0,它表示一个任务,如果它是-1,它表示等待。 如果它读取 -1,它会在继续之前使用以下循环等待广播

while (str->conn == -1) {
    else {
        if (pthread_cond_wait(&str->cond,&str->mutex)) {
            if (pthread_mutex_unlock(&str->mutex)) { }
            return NULL;
        }
        printf("here b3\n");
    }
}

现在,我的问题是,当 cond 变量被广播时 pthread_cond_broadcast(&thr->cond) 其中 thr 是 thread_st 类型,所有线程都打印“here b3”语句。为了理智,我已经测试过使用 在此处创建 thread_st 数组(再次删除错误处理)

struct thread_st pool[TP_SIZE];
for (i = 0; i < TP_SIZE; i++) {
    pool[i].conn = -1;
    if (pthread_mutex_init(&pool[i].mutex,NULL)) { }
    if (pthread_cond_init(&pool[i].cond,NULL)) { }
    if (pthread_create(&(pool[i].thr), NULL,worker_thr_routine, pool)) { }
}

有什么想法吗?这是我第一次真正尝试使用 cond 和 mutex 变量,所以如果我很愚蠢,请告诉!

谢谢

更新 线程只响应位于数组第一个结构中的条件变量的广播。

更新 2 找到了。原来我是个白痴。在我调用 pthread create 的地方,我通过了整个池。我只是想通过 pool[i]

【问题讨论】:

  • while (str-&gt;conn == -1) { else { 显然不是有效的 C 代码。遗漏了什么?
  • 顺便说一句,你处理失败返回的习语看起来有问题......
  • 有一个 if there 检查停止标志。在每组空括号中都有一个 perror 和 return 语句。我也即将更新帖子,因为进一步的测试给了我更多的细节

标签: c pthreads posix mutex


【解决方案1】:

您将对数组 pool 的引用传递给所有线程,因此(我猜,因为您的 OP 中缺少代码)每个线程都引用数组的第一个元素。

您可能想更改以下行:

if (pthread_create(&(pool[i].thr), NULL,worker_thr_routine, pool)) 

成为:

if (pthread_create(&(pool[i].thr), NULL,worker_thr_routine, pool + i)) 

将引用传递给线程函数pool当前 线程特定条目。

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2023-04-07
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多