条件变量
当一个线程互斥地访问某个变量时,它可能发现在其它线程改变状态之前,它什么也做不了。
例如 : 一个线程访问队列时,发现队列为空,它只能等待,直到其它线程将一个节点添加到队列中。类似这种情况就需要用到条件变量。
- 条件变量是用来实现同步机制的
同步概念与竞态条件 :
同步: 在保证数据安全的前提下,让线程能够按照某种特定的顺序访问临界资源,从而有效避免饥饿问题,叫做同步
竞态条件: 因为时序问题,而导致程序异常,称之为竞态条件。
条件变量函数 :
- 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;
}
运行结果: