gpt4 book ai didi

c - 为什么 pthread_cond_signal 不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 05:41:42 25 4
gpt4 key购买 nike

我目前正在学习 POSIX 线程 (pthread)。

我现在创建了一个简单的程序,它将共享值增加 7 直到超过 10000,然后它应该向下一个线程发出条件信号,将其减少 3 直到低于 1000。最后它应该将结果除以 2 和 main应该输出结果。

My code :

pthread_t threads[3];
pthread_cond_t cond_a, cond_b;
pthread_mutex_t mutex;

int counter;

void * worker_one();
void * worker_two();
void * worker_three();

int main(int argv, const char ** argc) {
counter = 0;

pthread_cond_init(&cond_a, NULL);
pthread_cond_init(&cond_b, NULL);
pthread_mutex_init(&mutex, NULL);

pthread_create(&threads[0], NULL, worker_one, NULL);
pthread_create(&threads[1], NULL, worker_two, NULL);
pthread_create(&threads[2], NULL, worker_three, NULL);

pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_join(threads[2], NULL);

printf("Value started at %d and ends with %d.\n", 0, counter);

return 0;
}

void * worker_one() {
printf("Worker one started.\n");

pthread_mutex_lock(&mutex);

printf("Worker one starting work.\n");
while (counter < 10000) {
counter += 7;
}

pthread_cond_signal(&cond_a);

printf("Worker one finished work with: %d.\n", counter);

pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}

void * worker_two() {
printf("Worker two started.\n");

pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond_a, &mutex);

printf("Worker two starting work.\n");
while (counter > 1000)
counter -= 3;

printf("Worker two finished work with: %d.\n", counter);

pthread_cond_signal(&cond_b);
pthread_mutex_unlock(&mutex);

sleep(1);

pthread_exit(NULL);
}

void * worker_three() {
printf("Worker three started.\n");

pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond_b, &mutex);

printf("Worker three starting work.\n");

counter /= 2;

printf("Worker three finished work with: %d.\n", counter);

pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}

出于某种原因,整个执行都卡在第一个线程周围。信号也被触发,但线程二没有反应。

谁能告诉我我做错了什么?

最佳答案

我在这里回答过类似的问题:pthread condition variables on Linux, odd behaviour .

问题是你甚至在测试你想要等待的条件为真之前就等待了。发生的情况是线程 1 在线程 2 等待之前发出信号,因此信号丢失,线程 2 将永远等待。

为了避免这种情况,首先测试你想要等待的是什么,然后只有当它不在这里时才等待。

编辑:好的,这是一个可能的解决方案,只有一个互斥锁和一个条件(未经测试)

线程 1:

pthread_mutex_lock(&mutex); 
while(thread_1_should_work == false){ // wait until the condition is satisfied
pthread_cond_wait(&cond, &mutex);
}

//at this point, we owe the mutex and we know thread_1_should_work is true;

// do work

thread_1_shoudl_work = false;
thread_2_should_work = true;

pthread_cond_broadcast(&cond); //wake up any waiting thread (if it's not their turn, they'll call wait again)
pthread_mutex_unlock(&mutex);

...等等。

关于c - 为什么 pthread_cond_signal 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16819169/

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