gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:51:29 29 4
gpt4 key购买 nike

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

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com