多线程,多接收模式串口类LsComm
2010-06-23 20:40:59 来源:WEB开发网主要做的工作是:
新建串口 this->m_pPort = new CSerialPort();
打开串口 this->m_pPort->Open
创建读取线程 this->m_pReadThread = new CReadComThread();
设立线程类与CComPort的关联关系this->m_pReadThread->BandSerialPort(this);
void CReadComThread::BandSerialPort(CComPort* pPort)
{
ASSERT(pPort);
this->m_pPort = pPort;
//创建异步读取事件
if(this->m_pPort->IsOverlapped())
{
this->m_ReadOverlapped.hEvent =::CreateEvent(NULL,false,false,NULL);
ASSERT(this->m_ReadOverlapped.hEvent);
this->m_BreakOverlapped.hEvent = ::CreateEvent(NULL,false,false,NULL);
ASSERT(this->m_BreakOverlapped.hEvent);
}
}
模式主要在线程执行的过程中发挥作用
3.串口的发送数据过程
DWORD CComPort::Output(void* pBuf,DWORD Count)
{
DWORD dwWriteBytes=0;
if(this->IsOverlapped())//异步模式
{
this->m_pPort->Write(pBuf,Count,this->m_WriteOverlapped);
if(WaitForSingleObject(this->m_WriteOverlapped.hEvent,INFINITE)==WAIT_OBJECT_0)
{
this->m_pPort->GetOverlappedResult(this->m_WriteOverlapped,dwWriteBytes,false);
}
}
else
dwWriteBytes= this->m_pPort->Write(pBuf,Count);
return dwWriteBytes;
}
再看this->m_pPort->Write(pBuf,Count);
实际上是:调用
DWORD CSerialPort::Write(const void* lpBuf, DWORD dwCount)
{
ASSERT(IsOpen());
ASSERT(!m_bOverlapped);
DWORD dwBytesWritten = 0;
if (!WriteFile(m_hComm, lpBuf, dwCount, &dwBytesWritten, NULL))
{
TRACE(_T("Failed in call to WriteFile\n"));
AfxThrowSerialException();
}
return dwBytesWritten;
}
或者是BOOL CSerialPort::Write(const void* lpBuf, DWORD dwCount, OVERLAPPED& overlapped, DWORD* pBytesWritten) 异步写串口的过程
更多精彩
赞助商链接