Linux :条件变量

条件变量

当一个线程互斥地访问某个变量时,它可能发现在其它线程改变状态之前,它什么也做不了。
例如 : 一个线程访问队列时,发现队列为空,它只能等待,直到其它线程将一个节点添加到队列中。类似这种情况就需要用到条件变量。

  • 条件变量是用来实现同步机制的
同步概念与竞态条件 :

同步: 在保证数据安全的前提下,让线程能够按照某种特定的顺序访问临界资源,从而有效避免饥饿问题,叫做同步
竞态条件: 因为时序问题,而导致程序异常,称之为竞态条件。

条件变量函数 :
  • init ( 初始化 )
int pthread_cond_init(pthread_cond_t *restrict cond,
                      const pthread_condattr_t *restrict attr);

参数:
cond —> 要初始化的条件变量
attr —> NULL

  • destroy ( 销毁 )
 int pthread_cond_destroy(pthread_cond_t *cond)
  • wait (等待条件满足)
 int pthread_cond_wait(pthread_cond_t *restrict cond, 
                       pthread_mutex_t *restrict mutex);

参数 :
cond —> 要在这个条件变量上等待 (等待挂起)
mutex —> 互斥量,后面详细解释 (释放锁)

  • 唤醒等待
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);

broadcast :唤醒多个被挂起的线程 (易引起惊群问题)
signal : 唤醒等待队列里的第一个线程
简单案例:

 #include <iostream>
 #include <pthread.h>
 #include <unistd.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sched.h>
 #include <string.h>
  
 pthread_mutex_t lock;
 pthread_cond_t cond;                                                                          
  
 void *thread_run(void *arg)
 {
     while(1){
         pthread_cond_wait ( &cond, &lock);
         std::cout << "active..." << std::endl;
     }
 }
  
 void *thread_signal(void *arg)
 {
     while(1){
         sleep(1);
         pthread_cond_signal(&cond);
     }
 }

 int main()
 {
     pthread_mutex_init;
     pthread_cond_init;
  
     pthread_t tid1,tid2;
     pthread_create(&tid1, NULL, thread_run, NULL);
     pthread_create(&tid2, NULL, thread_signal, NULL);
  
     pthread_join( tid1, NULL);
     pthread_join( tid2, NULL);
 
     pthread_mutex_destroy(&lock);
     pthread_cond_destroy(&cond);
   
     return 0;
 }                                          

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值