1、函数用法
(1)初始化条件变量
#include <pthread.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 初始化条件变量
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
// if(attr == NULL) -> 默认初始化;else -> 以attr属性初始化条件变量
int pthread_cond_destroy(pthread_cond_t *cond); // 销毁条件变量
返回值:成功返回0,失败返回错误号
(2)使用条件变量
条件变量和互斥量一同使用
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); // 阻塞等待信号
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime); // 超时等待信号
pthread_cond_wait函数流程:
1、给mutex解锁;2、等待条件;3、条件触发,mutex加锁。(3步是原子操作)
// 所谓原子操作是指不会被线程调度机制打断的操作,即第三步是条件触发和mutex加锁都成功
int pthread_cond_signal(pthread_cond_t *cond); // 发送给一个或多个线程信号
int pthread_cond_broadcast(pthread_cond_t *cond); // 发送给全部线程信号
返回值:成功返回0,失败返回错误号
/*************************************************************************
> File Name: cond.c
> Author: hsz
> Mail:
> Created Time:
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <errno.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t *gpCond = &cond;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t *gpMutex = &mutex;
int msleep(uint32_t ms)
{
struct timeval time;
int second = ms / 1000;
int us = (ms - second * 1000) * 1000;
time.tv_sec = ms / 1000;
time.tv_usec = us;
return select(0, NULL, NULL, NULL, &time);
}
void postSignal(int arg)
{
//pthread_cond_signal(gpCond);
pthread_cond_broadcast(gpCond);
}
void *thread1(void *arg)
{
while (1)
{
pthread_cond_wait(gpCond, gpMutex);
printf("**thread1 obtained mutex\n");
msleep(100);
pthread_mutex_unlock(gpMutex);
printf("**thread1 unlock mutex\n");
}
}
void *thread2(void *arg)
{
while (1)
{
pthread_cond_wait(gpCond, gpMutex);
printf("--thread2 obtained mutex\n");
msleep(200);
pthread_mutex_unlock(gpMutex);
printf("--thread2 unlock mutex\n");
}
}
int main(char **argv, int argc)
{
signal(SIGALRM, postSignal);
pthread_t tid[2];
pthread_create(&tid[0], NULL, thread1, NULL);
pthread_create(&tid[1], NULL, thread2, NULL);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}