线程同步——条件变量

线程同步的第二种方法:

条件变量初始化:

#include <pthread.h>
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);

使用 pthread_cond_init()函数初始化条件变量,当不再使用时,使用 pthread_cond_destroy()销毁条件变量。

通知和等待条件变量

#include <pthread.h>
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);

int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
  • pthread_cond_signal()函数至少能唤醒一个线程,
  • pthread_cond_broadcast()函数则能唤醒所有线程
  • pthread_cond_wait()函数将线程设置为等待状态(阻塞)。

pthread_cond_wait()函数的函数功能如同注释的一样,通过互斥锁实现;

 条件变量的判断条件

使用 while 循环,而不是 if 语句,这是一种通用的设计原则

条件变量的属性

 一般先解锁后发通知;

代码实例:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
static pthread_mutex_t mutex; //定义互斥锁
static pthread_cond_t cond; //定义条件变量
static int g_avail = 0; //全局共享资源
/* 消费者线程 */
static void *consumer_thread(void *arg)
{
for ( ; ; ) {
pthread_mutex_lock(&mutex);//上锁
while (0 >= g_avail)
pthread_cond_wait(&cond, &mutex);//等待条件满足
while (0 < g_avail)
g_avail--; //消费
pthread_mutex_unlock(&mutex);//解锁
}
return (void *)0;
}
/* 主线程(生产者) */
int main(int argc, char *argv[])
{
pthread_t tid;
int ret;
/* 初始化互斥锁和条件变量 */
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
/* 创建新线程 */
ret = pthread_create(&tid, NULL, consumer_thread, NULL);
if (ret) {
fprintf(stderr, "pthread_create error: %s\n", strerror(ret));
exit(-1);
}
for ( ; ; ) {
pthread_mutex_lock(&mutex);//上锁
g_avail++; //生产
pthread_mutex_unlock(&mutex);//解锁
pthread_cond_signal(&cond);//向条件变量发送信号
}
exit(0);
}

最近因为  感情原因  ,要了自己半条命,

但人生还是得继续,

“凡是人间的灾难,无论落到谁头上,谁都得受着,而且都受得了——只要他不死。至于死,那更是一件容易的事了。”——《周国平文集》

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值