Linux线程管理必备:互斥量与条件变量
作者:网络转载 发布时间:[ 2013/1/30 10:04:08 ] 推荐标签:
四、线程管理相关代码
//省略了线程互斥量以及条件变量的初始化
//线程管理:阻塞sec秒读取线程信息
//三个参数分别为:线程信息、线程ID、超时秒数
bool ManagePthread_TimeReadSignal(PTHREAD_BUF *rbuf, PTHREAD_ID thread_num, int sec)
{
bool b_valid = false;
struct timespec to;
int err;
to.tv_sec = time(NULL) + sec;
to.tv_nsec = 0;
//上锁
pthread_mutex_lock(&managePthread.g_pthread_mutex[thread_num]);
//超时sec秒阻塞等待,类似select
err = pthread_cond_timedwait(&managePthread.g_pthread_cond[thread_num], &managePthread.g_pthread_mutex[thread_num], &to);
if(err == ETIMEDOUT)
{
pthread_mutex_unlock(&managePthread.g_pthread_mutex[thread_num]);
return false;
}
//获取线程信息
if(managePthread.g_pthread_info[thread_num] == WRITE_FLAG)
{
managePthread.g_pthread_info[thread_num] = READ_FLAG;
memcpy((PTHREAD_BUF *)rbuf, (PTHREAD_BUF *)&managePthread.g_pthread_buf[thread_num], sizeof(PTHREAD_BUF));
b_valid = true;
}
//解锁
pthread_mutex_unlock(&managePthread.g_pthread_mutex[thread_num]);
return b_valid;
}
//阻塞读取线程信息
bool ManagePthread_ReadSignal(PTHREAD_BUF *rbuf, PTHREAD_ID thread_num, bool wait)
{
bool b_valid = false;
pthread_mutex_lock(&managePthread.g_pthread_mutex[thread_num]);
if(wait == true)
pthread_cond_wait(&managePthread.g_pthread_cond[thread_num], &managePthread.g_pthread_mutex[thread_num]);
if(managePthread.g_pthread_info[thread_num] == WRITE_FLAG)
{
managePthread.g_pthread_info[thread_num] = READ_FLAG;
memcpy((PTHREAD_BUF *)rbuf, (PTHREAD_BUF *)&managePthread.g_pthread_buf[thread_num], sizeof(PTHREAD_BUF));
b_valid = true;
}
pthread_mutex_unlock(&managePthread.g_pthread_mutex[thread_num]);
return b_valid;
}
//激活/发送线程信息
bool ManagePthread_SendSignal(PTHREAD_BUF *sbuf, PTHREAD_ID thread_num)
{
bool b_valid = false;
pthread_mutex_lock(&managePthread.g_pthread_mutex[thread_num]);
managePthread.g_pthread_info[thread_num] = WRITE_FLAG;
if(sbuf)
{
memcpy((PTHREAD_BUF *)&managePthread.g_pthread_buf[thread_num], (PTHREAD_BUF *)sbuf, sizeof(PTHREAD_BUF));
}
pthread_mutex_unlock(&managePthread.g_pthread_mutex[thread_num]);
pthread_cond_signal(&managePthread.g_pthread_cond[thread_num]);
b_valid = true;
return b_valid;
}
//广播
bool ManagePthread_BroadcastSignal(PTHREAD_BUF *sbuf, PTHREAD_ID thread_num)
{
bool b_valid = false;
pthread_mutex_lock(&managePthread.g_pthread_mutex[thread_num]);
managePthread.g_pthread_info[thread_num] = WRITE_FLAG;
memcpy((PTHREAD_BUF *)&managePthread.g_pthread_buf[thread_num], (PTHREAD_BUF *)sbuf, sizeof(PTHREAD_BUF));
pthread_mutex_unlock(&managePthread.g_pthread_mutex[thread_num]);
pthread_cond_broadcast(&managePthread.g_pthread_cond[thread_num]);
b_valid = true;
return b_valid;
}
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11