MFC(4) MFC中使用事件(event)来线程同步

来源:互联网 发布:java转换url编码 编辑:程序博客网 时间:2024/05/07 21:35

MFC中的Event以类比linux中的cond,条件变量——wait and signal


OpenDevice.h

#pragma onceclass OpenDevice{public:OpenDevice(void);~OpenDevice(void);public:CWinThread *m_pThread;HANDLEm_hCom;HANDLE m_hWakeupEvent;BOOL Init(void);BOOL OpenSerial(void);static UINT work_thread(void *args);BOOL m_SetEvent(void);};

OpenDevice.c

#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;}#endifTRACE("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();}



1 0
原创粉丝点击