MFC中的Event以类比linux中的cond,条件变量——wait and signal
OpenDevice.h
#pragma once class OpenDevice { public: OpenDevice(void); ~OpenDevice(void); public: CWinThread *m_pThread; HANDLE m_hCom; HANDLE m_hWakeupEvent; BOOL Init(void); BOOL OpenSerial(void); static UINT work_thread(void *args); BOOL m_SetEvent(void); };
#include "stdafx.h" #include "OpenDevice.h" OpenDevice::OpenDevice(void) { m_hCom = NULL; m_hWakeupEvent = NULL; m_pThread = NULL; } OpenDevice::~OpenDevice(void) { if(NULL != m_hCom) { CloseHandle(m_hCom); m_hCom = NULL; } if(NULL != m_hWakeupEvent) { CloseHandle(m_hWakeupEvent); m_hWakeupEvent = NULL; } } //初始化事件,创建子线程 BOOL OpenDevice::Init(void) { //创建并初始化事件 m_hWakeupEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(NULL == m_hWakeupEvent) { TRACE(strerror(GetLastError())); return FALSE; } //创建子线程(创建的时候立即运行) m_pThread = AfxBeginThread(work_thread, this); if(NULL == m_pThread) { TRACE(strerror(GetLastError())); return FALSE; } return TRUE; } BOOL OpenDevice::OpenSerial(void) { if(NULL == m_hWakeupEvent) { return FALSE; } else { ResetEvent(m_hWakeupEvent); } //等待串口设备插入:当用户点击打开按钮时,发送事件,则WaitForSingleObject返回 while(1) { TRACE("wait for event...\n"); #if 1 //手动重置事件 ResetEvent(m_hWakeupEvent); DWORD res = WaitForSingleObject(m_hWakeupEvent, INFINITE); // if(WAIT_OBJECT_0 != res) { TRACE(strerror(GetLastError())); continue; } #endif TRACE("start CreateFile...\n"); //打开串口文件 m_hCom = CreateFile( "COM3", GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if(INVALID_HANDLE_VALUE == m_hCom) { TRACE(strerror(GetLastError())); AfxMessageBox("串口打开失败!"); } else { TRACE("open successful\n"); return TRUE; } } } UINT OpenDevice::work_thread(void *args) { OpenDevice *pOpenDevice = (OpenDevice *)args; BOOL res = pOpenDevice->OpenSerial(); if(TRUE == res) { while(1) { TRACE("read and write serial!\n"); Sleep(5000); } } return 0; } BOOL OpenDevice::m_SetEvent(void) { SetEvent(m_hWakeupEvent); return TRUE; }
void CEventDlg::OnBnClickedOpen() { // TODO: 在此添加控件通知处理程序代码 m_openDevice.m_SetEvent(); }