一、前言
开发中上位机获取或设置下位机参数的接口,有阻塞、非阻塞两种:
1、API非阻塞,异步回调返回结果
2、API阻塞,超时或直接返回结果
对于应用层调用者来说,阻塞API更方便,而要实现阻塞API在windows可使用原生Event来实现。
相关链接:
createEventW 函式 (synchapi.h) - Win32 apps | Microsoft Learn
pulseEvent 函数 (winbase.h) - Win32 apps | Microsoft Learn
WaitForSingleObject | Microsoft Learn
二、Event使用
1、创建Event
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2、等待Event信号或超时
//等待事件通知或超时
WaitForSingleObject(hEvent, 5000);
3、设置Event信号
SetEvent(hEvent);
//或
PulseEvent(hEvent);
4、关闭Event
if (hEvent)
{CloseHandle(hEvent);hEvent = NULL;
}
三、注意事项
1、SetEvent在WaitForSingleObject之前调用也会生效
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);qDebug("SetEvent");
SetEvent(hEvent);
qDebug("WaitForSingleObject before");
WaitForSingleObject(hEvent, INFINITE); //永不超时
qDebug("WaitForSingleObject after");
输出
2、ResetEvent清空Event信号
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);qDebug("SetEvent");
SetEvent(hEvent);
qDebug("ResetEvent");
ResetEvent(hEvent);
qDebug("WaitForSingleObject before");
WaitForSingleObject(hEvent, INFINITE);
qDebug("WaitForSingleObject after");
输出
3、PulseEvent 可以将事件对象的状态设置为已发出信号,并将其重置为非信号
1) 重置非信号测试
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);qDebug("PulseEvent");
PulseEvent(hEvent);
qDebug("WaitForSingleObject before");
WaitForSingleObject(hEvent, INFINITE);
qDebug("WaitForSingleObject after");
输出
2)设置信号
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);std::thread thr([=]() {Sleep(1000);qDebug("PulseEvent");PulseEvent(hEvent);
});qDebug("WaitForSingleObject before");
WaitForSingleObject(hEvent, INFINITE);
qDebug("WaitForSingleObject after");
输出