C pthread_cond_broadcast 似乎正在广播到所有 cond 变量

标签 c pthreads posix mutex

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

struct thread_st
{
    pthread_t thr;

    int conn;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
};

conn 指示线程是否有工作要做。如果>=0则表示正在执行任务,如果为-1则表示等待。 如果它读取到 -1,它会在继续之前使用以下循环等待广播,我已经删除了一些错误处理,因此 else 等将 block 缩小到所需的内容

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]

最佳答案

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

您可能想要更改以下行:

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

成为:

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

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

关于C pthread_cond_broadcast 似乎正在广播到所有 cond 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15081512/

相关文章:

c - 串行端口输入缓冲区的字节数

c - 二分查找的两个先决条件是什么?

c - 关于使用 size_t

c - C 中的 POSIX 到 DOS 以及 DOS 到 POSIX 路径转换

c - posix 线程 (pthreads) 标准

c - void *function() 应该使用什么返回类型?

c - MPI:处理器在单个 MPI 进程上无法达到 100%

c - 使用多线程时如何检测数据丢失的位置

c++ - C/C++ pthread 信号和指针

linux - 如何为GNU find适本地限定-or运算符?如何找到指向可执行文件的符号链接(symbolic link)?