【学习笔记】条件变量+互斥锁解决问题
【学习笔记】条件变量+互斥锁解决问题
一、问题
存在一个线程,这个线程执行一次就会休眠一分钟,但是某个动作触发的时候需要这个线程执行一次。
二、解决问题
一个线程在while(1)中每次执行
pthread_cond_t auth_cond; //条件变量 pthread_mutex_t auth_mutex; //时间互斥锁 pthread_cond_init(&gpHseriesBox->DeviceManage->auth_cond, NULL);pthread_mutex_init(&gpHseriesBox->DeviceManage->auth_mutex, NULL);void *pthread_func(void * arg)
{while(true){struct timespec timeout; clock_gettime(CLOCK_REALTIME, &timeout);timeout.tv_sec += 60; // 计算超时时间(当前时间 + 60秒)休眠60秒pthread_mutex_lock(&stu->auth_mutex);// 执行业务代码// 等待触发信号或超时(可以被打断的休眠60秒)int result = pthread_cond_timedwait(&stu->auth_cond, &stu->auth_mutex, &timeout);if (result == ETIMEDOUT) //超时60s{// 自己等待超时60Spthread_mutex_unlock(&stu->auth_mutex);continue;}// 被条件变量触发pthread_mutex_unlock(&stu->auth_mutex);DEBUG_NOTICE("[auth] pthread_authorization_func Start by cond");}
} //只需要在调用的地方调用一次这个接口即可,记得加锁: pthread_cond_signal(&auth_cond); // 立即唤醒一次睡眠中的线程
你可以理解为下面的代码就是sleep(60),只是这个1分钟是可以随时被打断的。
// 等待触发信号或超时(可以被打断的休眠60秒)int result = pthread_cond_timedwait(&stu->auth_cond, &stu->auth_mutex, &timeout);if (result == ETIMEDOUT) //超时60s{// 自己等待超时60Spthread_mutex_unlock(&stu->auth_mutex);continue;}// 被条件变量触发pthread_mutex_unlock(&stu->auth_mutex);DEBUG_NOTICE("[auth] pthread_authorization_func Start by cond");