生产者:每次对一个全局变量加1,并唤醒消费者输出该变量的值
消费者:每次等待生产者对全局变量加1,之后输出全局变量的值
期望是消费者每次从1开始,依次打印全局变量的值。
代码如下:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int val;
pthread_mutex_t val_lock;
pthread_cond_t val_cond;
void *producer_thread(void *args)
{
while (1) {
pthread_mutex_lock(&val_lock);
val++;
pthread_cond_signal(&val_cond);
pthread_mutex_unlock(&val_lock);
sleep(1);
}
return NULL;
}
void *consumer_thread(void *args)
{
while (1) {
pthread_mutex_lock(&val_lock);
pthread_cond_wait(&val_cond, &val_lock);
printf("consumer_thread woke up, val is: %d\n", val);
pthread_mutex_unlock(&val_lock);
sleep(1);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t producer_tid;
pthread_t consumer_tid;
pthread_mutex_init(&val_lock, NULL);
pthread_cond_init(&val_cond, NULL);
pthread_create(&producer_tid, NULL, producer_thread, NULL);
pthread_create(&consumer_tid, NULL, consumer_thread, NULL);
pthread_mutex_destroy(&val_lock);
pthread_cond_destroy(&val_cond);
pthread_join(producer_tid, NULL);
pthread_join(consumer_tid, NULL);
while (1)
sleep(1);
return 0;
}
可是实际的效果如下:
consumer_thread woke up, val is: 1
consumer_thread woke up, val is: 2
consumer_thread woke up, val is: 2
consumer_thread woke up, val is: 4
consumer_thread woke up, val is: 5
consumer_thread woke up, val is: 6
疑问:
1、这段代码处理线程互斥和同步的用法对吗?特别是对条件变量的用法。
2、为什么红色区域的输出会有两次的值都是2呢?
2 个解决方案
#1
打印之前判断是否还是上次的值不就行了
#2
用法不对,生产者应该这样 pthread_mutex_lock(&val_lock);
val++;
pthread_mutex_unlock(&val_lock);
pthread_cond_signal(&val_cond);
先解锁,再去发送信号....
val++;
pthread_mutex_unlock(&val_lock);
pthread_cond_signal(&val_cond);
先解锁,再去发送信号....
#1
打印之前判断是否还是上次的值不就行了
#2
用法不对,生产者应该这样 pthread_mutex_lock(&val_lock);
val++;
pthread_mutex_unlock(&val_lock);
pthread_cond_signal(&val_cond);
先解锁,再去发送信号....
val++;
pthread_mutex_unlock(&val_lock);
pthread_cond_signal(&val_cond);
先解锁,再去发送信号....