//
//  The CommThread Function.
///线程函数
///监视线程的大致流程:
///检查串口-->进入循环{WaitCommEvent(不阻塞询问)询问事件-->如果有事件来到-->到相应处理(关闭\读\写)}
//
UINT CSerialPort::CommThread(LPVOID pParam)
{
// Cast the void pointer passed to the thread back to
// a pointer of CSerialPort class
///CSerialPort类的指针
CSerialPort *port = (CSerialPort*)pParam;

// Set the status variable in the dialog class to
// TRUE to indicate the thread is running.
///TRUE表示线程正在运行
port->m_bThreadAlive = TRUE;
       .....
       // Main wait function.  This function will normally block the thread
// until one of nine events occur that require action.
///等待3个事件:关断/读/写,有一个事件发生就返回
Event = WaitForMultipleObjects(3, ///3个事件     我点击发送 但Event一直是1 发送卡死了
port->m_hEventArray, ///事件数组
FALSE, ///有一个事件发生就返回
INFINITE);///超时时间 switch (Event)
{
case 0:
{
// Shutdown event.  This is event zero so it will be
// the higest priority and be serviced first.
///关断事件,关闭串口
CloseHandle(port->m_hComm);
port->m_hComm=NULL;
port->m_bThreadAlive = FALSE;

// Kill this thread.  break is not needed, but makes me feel better.
AfxEndThread(100); break;
}
case 1: /// read event将定义的各种消息发送出去
{
memset(&comstat, 0, sizeof(COMSTAT)); 
GetCommMask(port->m_hComm, &CommEvent);
if (CommEvent & EV_RXCHAR)//接收到字符,并置于输入缓冲区中
// Receive character event from port.
ReceiveChar(port, comstat);
/*if (CommEvent & EV_CTS)//CTS信号状态发生变化
::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_CTS_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);*/
if (CommEvent & EV_BREAK)//输入中发生中断
::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_BREAK_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
if (CommEvent & EV_ERR)//发生线路状态错误,线路状态错误包括CE_FRAME,CE_OVERRUN和CE_RXPARITY 
::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_ERR_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
if (CommEvent & EV_RING)//检测到振铃指示
::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RING_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
if (CommEvent & EV_RXFLAG)//接收到事件字符,并置于输入缓冲区中
::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RXFLAG_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
break;
}  
case 2: /// write event发送数据
{
// Write character event from port
WriteChar(port);
break;
}
     
}
求指教啊,我弄了好久了,都找不到原因,我一直在调用串口发送函数,不停的发送,点久了就发送不出去了!!!求大神只条明路啊。。

解决方案 »

  1.   

    Multiple Threads in the User Interface http://msdn.microsoft.com/zh-cn/library/ms810439.aspx
      

  2.   

    SetEvent(m_hWriteEvent)  不能触发WriteChar函数   真的 好急啊。。求高手 怎么弄的
      

  3.   

    1.贴代码的时候能不能用源码格式,看着累!2 SerialPort类 自己封装的?3 最好再仔细看看win32串口编程,还有楼主对多线程好像也不怎么理解。
      

  4.   

    @tajon1226 能否加个QQ 353356315   谢谢 谢谢!!
      

  5.   

    http://wenku.baidu.com/link?url=DPQlrIq36d2iHoLUe_DSO1duhZFQuHTYBjH8iabQ79ENCj0bR0jP5EG2Ref3BTdAbfIZfbfs7CMr8W2aJtx4ly0yQBiRSVI-LalJO17cjZ3看会这个。
    再看windows编程的互斥
      

  6.   

    记得CodeProject有CSerialPort类,你到那个上面直接下载源代码使用就可以了,不需要自己去做封装了。