|
这是我写的一个简单串口读线程,将线程函数封装在了类里面
- class CCESeries:public CGPSpro
- {
- public:
- //打开串口
- BOOL OpenPort(PTCHAR Port);
- CCESeries();
- virtual ~CCESeries();
-
- HANDLE m_hReadThread; //读线程句柄
- DWORD m_dwReadThreadID; //读写线程ID标识
-
- static DWORD WINAPI ReadThreadFunc(LPVOID lparam);
- static DWORD WINAPI WriteThreadFunc(LPVOID lparam);
- };
复制代码- BOOL CCESeries::OpenPort(PTCHAR Port)
- {
- BOOL ret = FALSE;
- if (m_hComm != INVALID_HANDLE_VALUE) //已经打开,直接返回
- {
- SerialErrorHandle(_T("<>Serial already opened\r\n"));
- return TRUE;
- }
- ::Sleep(10000);
- m_hComm = ::CreateFile(Port, //以同步读取方式打开串口
- GENERIC_READ,// | GENERIC_WRITE, //允许读
- 0, //独占方式
- NULL,
- OPEN_EXISTING, //打开而不是创建
- 0,
- NULL);
- if (m_hComm == INVALID_HANDLE_VALUE) // 无效句柄,返回。
- {
- SerialErrorHandle(_T("<>Create COM failed\r\n"));
- return FALSE;
- }
- [color=#FF0000]m_hReadThread = CreateThread(NULL,0,ReadThreadFunc,this,0,&m_dwReadThreadID);//创建读串口线程[/color]
- return TRUE;
- }
复制代码- DWORD CCESeries::ReadThreadFunc(LPVOID lparam) //串口读线程函数
- {
- try
- {
- [color=#FF0000]CCESeries *ceSeries = (CCESeries*)lparam;[/color]
-
- DWORD evtMask;
- BYTE * readBuf = NULL;//读取的字节
- DWORD actualReadLen=0;//实际读取的字节数
- DWORD willReadLen;
-
- //清空串口
- PurgeComm(ceSeries->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR );
- SetCommMask (ceSeries->m_hComm, EV_RXCHAR);// | EV_CTS | EV_DSR );
-
- while (TRUE)
- {
- if (WaitCommEvent(ceSeries->m_hComm,&evtMask,0))
- {
- SetCommMask (ceSeries->m_hComm, EV_RXCHAR);// | EV_CTS | EV_DSR );
- //表示串口收到字符
- if (evtMask & EV_RXCHAR)
- {
- willReadLen = 512;//cmState.cbInQue ;//接收缓冲区中存储的待读取的字符数
- if (willReadLen <= 0)
- {
- continue;
- }
- readBuf = new BYTE[willReadLen+1];
-
- ReadFile(ceSeries->m_hComm, readBuf, willReadLen, &actualReadLen,0);
- readBuf[actualReadLen]=0;
-
- //如果读取的数据大于0,
- if (actualReadLen>0)
- {
- //to do something here
- }
- }
-
- //如果收到读线程退出信号,则退出线程
- if (WaitForSingleObject(ceSeries->m_hReadCloseEvent,300) == WAIT_OBJECT_0)
- {
- break;
- }
- delete readBuf;
- }
- }
- catch (...)
- {
- RETAILMSG(DBGMSGON, (_T("<>Serial read EXCEPTION\r\n")));
- }
-
- return 0;
- }
复制代码
下面这个是什么意思
CCESeries *ceSeries = (CCESeries*)lparam
在创建线程的时候传进的参数是this
谢谢
|
|