一、前言
以前我写超时,一般都是调用GetTickCount()函数来做,后来发现VS中有一个event的操作可以直接用来做超时,所以简单的研究了一下
二、代码
2.1 main
#include "Event.h"
#include <thread>
void Test()
{
cout << "Test" << endl;
Sleep(3000); // 时间1
cout << "complete event!" << endl;
}
int main() {
CEvent e;
thread t1(&CEvent::StartEvent, &e, Test);
t1.detach();
thread t2(&CEvent::WaitSignal, &e, 5000); // 时间2 当时间2小于时间1 则等待超时
t2.detach();
cin.ignore();
}
2.2 Event.h
#pragma once
#include <windows.h>
#include <iostream>
using namespace std;
class CEvent
{
public:
CEvent();
~CEvent();
bool StartEvent(void(*func)());
int WaitSignal(int timeOut);
private:
HANDLE m_hEvent;
};
2.3 Event.cpp
#include "Event.h"
CEvent::CEvent()
{
if (NULL == m_hEvent)
{
m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
return;
}
}
CEvent::~CEvent()
{
}
bool CEvent::StartEvent(void(*func)())
{
cout << "Start event!" << endl;
func(); // 写实现函数
return SetEvent(m_hEvent);
}
int CEvent::WaitSignal(int timeOut)
{
int ncode = WaitForSingleObject(m_hEvent, timeOut);
if (ncode == 0) {
cout << "wait successful!" << endl;
}
if (ncode == WAIT_TIMEOUT) {
cout << "wait time out!" << endl;
}
ResetEvent(m_hEvent);
return ncode;
}