条件变量是一种线程间同步的机制,使用条件变量为了防止竞争,都会和一个互斥锁配合使用
操作函数
pthread_cond_init(&cond, NULL); /* 动态初始化条件变量 */
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; /* 静态初始化条件变量 */
pthread_cond_wait(&cond); /* 等待条件变量触发 */
pthread_cond_timedwait(&cond); /* 超时等待条件变量触发 */
pthread_cond_signal(&cond); /* 激活一个等待该条件的线程,单播 */
pthread_cond_broadcast(&cond); /* 激活所有等待该条件的线程,广播 */
pthread_cond_destroy(&cond); /* 销毁条件变量 */
线程同步实例
下面的例子目的是让thread_2先于thread_1执行
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
void *thread_1(void *data)
{
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
printf("%s\n", __func__);
pthread_mutex_unlock(&lock);
}
void *thread_2(void *data)
{
pthread_mutex_lock(&lock);
printf("%s\n", __func__);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
int main(int argc, char const *argv[])
{
pthread_t pid[2];
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&pid[0], NULL, thread_1, NULL);
pthread_create(&pid[1], NULL, thread_2, NULL);
pthread_join(pid[0], NULL);
pthread_join(pid[1], NULL);
pthread_mutex_unlock(&lock);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
条件变量始终都会和一个互斥锁配合使用,当pthread_cond_wait()被调用阻塞住线程的时候,lock会被自动释放,当信号来的时候会自动上锁。thread_1获取到互斥锁之后,因为条件变量的存在,thread_1被阻塞住,互斥锁自动释放掉,当条件变量满足条件之后系统会将互斥锁再重新锁上
单播和广播实例
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
void *thread_1(void *data)
{
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
printf("%s\n", __func__);
pthread_mutex_unlock(&lock);
}
void *thread_2(void *data)
{
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
printf("%s\n", __func__);
pthread_mutex_unlock(&lock);
}
int main(int argc, char const *argv[])
{
int cid = 0;
pthread_t pid[2];
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&pid[0], NULL, thread_1, NULL);
pthread_create(&pid[1], NULL, thread_2, NULL);
while (1) {
scanf("%d", &cid);
getchar();
if (cid == 1) {
pthread_cond_signal(&cond); /* 单播,向其中一个线程发送信号 */
} else if (cid == 2) {
pthread_cond_broadcast(&cond); /* 广播,向所有等待条件变量的线程发送信号 */
} else if (cid == 3) {
break;
}
}
pthread_join(pid[0], NULL);
pthread_join(pid[1], NULL);
pthread_mutex_unlock(&lock);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
pthread_cond_signal()发送的是单播信号,也就是thread_1和thread_2中会有一个运行,发送几次就会有几个线程接收到信号。
pthread_cond_broadcast()发送的是广播信号,当它执行的时候thread_1和thread_2会一起收到信号,事实上无论有多少个线程在等待cont条件,如果想让它们都运行起来,通过pthread_cond_broadcast()广播即可