Why does pthread_cond_signal not work?【转】

简介: 转自:http://stackoverflow.com/questions/16819169/why-does-pthread-cond-signal-not-work# 0 down vote favorite   I am currently learing all around POSIX threads (pthread).

转自:http://stackoverflow.com/questions/16819169/why-does-pthread-cond-signal-not-work#

0 down vote favorite

 

I am currently learing all around POSIX threads (pthread).

I now have created a simple program which increased a shared value by 7 until above 10000 then it should signal a condition to the next thread which decreases it by 3 until under 1000. At last it should divide the result through 2 and main should output the result.

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);
}

For some reason the whole execution hangs around the first thread. The signal is also fired but thread two does not react.

Can somebody tell me what I am doing wrong?

 
Could somebody tell me why down vote? – bodokaiser May 29 '13 at 16:23
    
I've moved the code from gist to SO. Don't just link to code on an external site, please include relevant code in the question. – user7116 May 29 '13 at 16:25
    
ok did not knew anything about this – bodokaiser May 29 '13 at 16:25

6 down vote accepted

 

I have answered a similar question here: pthread condition variables on Linux, odd behaviour.

The problem is that you wait before even testing the condition you want to wait for is true. What happens is that thread 1 signals before thread 2 is waiting, therefore the signal is lost and thread 2 will be waiting forever.

In order to avoid this, first test what you want to wait for, then wait only if it's not here.

EDIT: Ok, here is a possible solution with only one mutex and one condtion (untested)

Thread 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); 
Is the testing case a simple external flag or something pthread internal? I use the example from computing.llnl.gov/tutorials/pthreads but there are no flags actually – bodokaiser May 29 '13 at 16:33
 
 
@bodokaiser: you'll have to make up a variable, but a simple boolean flag will do. Spurious wakeups are a reality unfortunately. – user7116 May 29 '13 at 16:35
 
@sixlettervariables so the main idea of conditions are just some more specific mutex signaling (with out the actual locking). Is this correct? – bodokaiser May 29 '13 at 16:36
 
Yes, in your case is thread_is_working flag would work (except that it has more than 6 letters :) I think the answer that the linked answer can help. – Ben May 29 '13 at 16:38
 
Actually, wait() releases the mutex and yield the thread atomically so that nothing happens while the thread is being yield. – Ben May 29 '13 at 16:41

 

【作者】 张昺华
【新浪微博】 张昺华--sky
【twitter】 @sky2030_
【facebook】 张昺华 zhangbinghua
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
目录
相关文章
|
程序员 C语言 C++
C语言中的goto语句:使用、争议与最佳实践
C语言中的goto语句:使用、争议与最佳实践
1208 1
|
消息中间件 存储 Kafka
深入Kafka:如何保证数据一致性与可靠性?
**Kafka一致性详解:** 讲解了幂等性如何通过ProducerID和SequenceNumber确保消息唯一,防止重复处理,维持数据一致性。Kafka利用Zookeeper进行控制器和分区Leader选举,应对节点变动,防止脑裂,确保高可用性。实例中,电商平台用Kafka处理订单,保证每个订单仅处理一次,即使在异常情况下。关注微信公众号“软件求生”获取更多技术内容。
1950 0
|
运维 应用服务中间件 nginx
运维(27)-部署流量代理(Nginx+haproxy)
运维(27)-部署流量代理(Nginx+haproxy)
261 0
P5318 【深基18.例3】查找文献
P5318 【深基18.例3】查找文献
P5318 【深基18.例3】查找文献
|
存储 缓存 关系型数据库
怎么减少行锁对性能的影响
怎么减少行锁对性能的影响
200 0
怎么减少行锁对性能的影响
|
SQL 存储 监控
直击阿里新一代数据库技术:如何实现极致弹性能力?
张瑞,阿里巴巴研究员,阿里集团数据库技术团队负责人,经历阿里数据库技术变革历程,连续六年作为数据库总负责人参与双11备战工作。今天,我们邀请他来分享新一代数据库技术在双11中的应用。
9183 0
|
新零售 运维 程序员
地摊经济引爆新零售思路——MVP一周精选 20200605
地摊经济是近几天全民热议的话题,本周我们为您带来阿里云 MVP们的看法。从鞋服业客户的增长大法到小微企业的独特技术运营理念,快来了解一下。
地摊经济引爆新零售思路——MVP一周精选 20200605
|
机器学习/深度学习 人工智能 物联网
|
3天前
|
云安全 人工智能 安全
AI被攻击怎么办?
阿里云提供 AI 全栈安全能力,其中对网络攻击的主动识别、智能阻断与快速响应构成其核心防线,依托原生安全防护为客户筑牢免疫屏障。