静态初始化,用于全局变量,存在内存静态区.data
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
PTHREAD_COND_INITIALIZER:一个条件变量结构体常量
动态初始化,用于局部变量,存在内存栈
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
cond:定义的条件变量
attr:条件变量作用于进程间还是线程间,NULL = 线程间
返回值:成功 = 0,失败 = !0
销毁条件变量,仍在使用时失败返回EBUSY
int pthread_cond_destroy(pthread_cond_t *cond)
cond:定义的条件变量
返回值:成功 = 0,失败 = !0
条件变量发信号唤醒线程
唤醒一个
int pthread_cond_signal(pthread_cond_t *cond)
唤醒全部
int pthread_cond_broadcast(pthread_cond_t *cond)
cond:定义的条件变量
返回值:成功 = 0,失败 = !0 。若当前没有线程等待通知,cond指向非法地址,返回EINVAL
等待条件变量的唤醒信号
休眠等待
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
在abstime时间内休眠等待
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
cond:定义的条件变量
mutex:等待之前需要解开的互斥锁
abstime:struct timespec结构体(秒,纳秒)
返回值:成功 = 0,失败 = !0
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pthread.h> //条件变量头文件
#include <semaphore.h>
//1.定义条件变量(加互斥锁)
pthread_cond_t cond;
pthread_mutex_t mutex;
//生产者线程
void *task1(){
while(1){
sleep(3);
//一定要注意所有线程同时都在运行,合理安排sleep位置,避免生产线程多运行一次的浪费
puts("生产者线程运行");
//3.条件变量给所有休眠进程发通知
pthread_cond_broadcast(&cond);
}
pthread_exit(NULL);
}
//消费者线程1
void *task2(){
while(1){
//3.1 上锁
pthread_mutex_lock(&mutex);
//3.2 休眠等待条件变量发通知
pthread_cond_wait(&cond, &mutex);
puts("消费者线程1运行");
//3.3 解锁
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
//消费者线程2
void *task3(){
while(1){
//3.1 上锁
pthread_mutex_lock(&mutex);
//3.2 休眠等待条件变量发通知
pthread_cond_wait(&cond, &mutex);
puts("消费者线程2运行");
//3.3 解锁
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
pthread_mutex_init(&mutex, PTHREAD_MUTEX_TIMED_NP);
pthread_t tid1, tid2, tid3;
//2.初始化条件变量
pthread_cond_init(&cond,NULL);
if(0 != pthread_create(&tid1, NULL, task1, NULL)){
fprintf(stderr, "pthread_create error\n");
exit(EXIT_FAILURE);
}
if(0 != pthread_create(&tid2, NULL, task2, NULL)){
fprintf(stderr, "pthread_create error\n");
exit(EXIT_FAILURE);
}
if(0 != pthread_create(&tid3, NULL, task3, NULL)){
fprintf(stderr, "pthread_create error\n");
exit(EXIT_FAILURE);
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
//4.销毁条件变量
pthread_cond_destroy(&cond);
return 0;
}