条件变量
1、使用全局变量进行轮训的方式
例如:有两个线程,线程1创建网络,线程2需要等待线程1创建网络完成后,才能给网络中设备发消息。
线程1的任务:
void* appProcess(void *argument)
{
int32_t status;
//Flush all messages from the que
do
{
status = rpcWaitMqClientMsg(50);
} while (status != -1);
devState = DEV_HOLD;
status = startNetwork();
if (status != -1)
{
consolePrint("Network up\n\n");
initDone = 1;
}
else
{
consolePrint("Network Error\n\n");
}
sysGetExtAddr();
OsalNvWriteFormat_t nvWrite;
nvWrite.Id = ZCD_NV_ZDO_DIRECT_CB;
nvWrite.Offset = 0;
nvWrite.Len = 1;
nvWrite.Value[0] = 1;
status = sysOsalNvWrite(&nvWrite);
while(1)
{
rpcWaitMqClientMsg(500);
usleep(10*1000);
}
return 0;
}
线程2的任务:
void *nwkMgmtTask(void *argument)
{
MgmtLqiReqFormat_t req;
req.DstAddr = 0;
req.StartIndex = 0;
while(1)
{
if(initDone) {
zdoMgmtLqiReq(&req);
}
sleep(1);
}
}
这里通过全局变量initDone作为条件变量。使用这种方法可以很简单的实现,但是会有一定的性能消耗,其还有一个点要好好把握,就是一次轮询没有结果后相隔多久进行下一次的轮询,间隔时间太短,消耗的CPU资源较多,间隔时间太长,不能很及时的响应请求。
所以这种方法不是推荐。
2、使用条件变量的线程同步(推荐)
采用阻塞和消息方式可以极大程度上减少资源的浪费以及增加实时性。
线程条件变量pthread_cond_t
线程等待某个条件
int pthread_cond_timedwait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,const struct timespec *restrict abstime);
int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
通知函数
通知所有的线程
int pthread_cond_broadcast(pthread_cond_t *cond);
只通知一个线程
int pthread_cond_signal(pthread_cond_t *cond);
void *nwkMgmtTask(void *argument)
{
MgmtLqiReqFormat_t req;
req.DstAddr = 0;
req.StartIndex = 0;
while(1)
{
pthread_mutex_lock(&network_mutex);
if (network_up == 0) {
pthread_cond_wait(&network_cond, &network_mutex);
dbg_print(PRINT_LEVEL_ERROR, "pthread_cond_wait ok\n");
}
pthread_mutex_unlock(&network_mutex);
zdoMgmtLqiReq(&req);
sleep(2);
}
}
void* appProcess(void *argument)
{
int32_t status;
//Flush all messages from the que
do
{
status = rpcWaitMqClientMsg(50);
} while (status != -1);
devState = DEV_HOLD;
status = startNetwork();
if (status != -1)
{
consolePrint("Network up\n\n");
network_up = 1;
}
else
{
consolePrint("Network Error\n\n");
}
pthread_mutex_lock(&network_mutex);
if (network_up == 1) {
pthread_cond_signal(&network_cond);
}
pthread_mutex_unlock(&network_mutex);
sysGetExtAddr();
OsalNvWriteFormat_t nvWrite;
nvWrite.Id = ZCD_NV_ZDO_DIRECT_CB;
nvWrite.Offset = 0;
nvWrite.Len = 1;
nvWrite.Value[0] = 1;
status = sysOsalNvWrite(&nvWrite);
while(1)
{
rpcWaitMqClientMsg(500);
usleep(10*1000);
}
return 0;
}