【发布时间】: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->conn == -1) { else {显然不是有效的 C 代码。遗漏了什么? -
顺便说一句,你处理失败返回的习语看起来有问题......
-
有一个 if there 检查停止标志。在每组空括号中都有一个 perror 和 return 语句。我也即将更新帖子,因为进一步的测试给了我更多的细节