WaitCommEvent in thread causing application to hang


2004-05-11 04:13:09 PM
cppbuilder11
A while ago I wrote a serial communications component TCOMPort, which uses
non-overlapped I/O and creates a second thread to monitor events like the
reception of a character, parity error, etc. Here's the code for the
thread's Execute() method:
void __fastcall TCOMThread::Execute()
{
DWORD EvtMask, Errors;
COMSTAT Status;
SetCommMask(COMPort->PortHandle, EV_ERR | EV_RXCHAR | EV_CTS | EV_DSR);
while (!Terminated)
{
WaitCommEvent(COMPort->PortHandle, &EvtMask, NULL);
ClearCommError(COMPort->PortHandle, &Errors, &Status);
if (EvtMask & EV_ERR)
{
// Handle error.
}
// Process other events.
}
}
PortHandle is a private data member of TCOMPort and TCOMThread is defined as
a friend class of TCOMPort.
The serial port is opened in the Open() method of TCOMPort:
bool __fastcall TCOMPort::Open ()
{
const char * const PortName[] = {"COM1", "COM2", "COM3", "COM4"};
PortHandle = CreateFile(PortName[FPort], GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
if (PortHandle == INVALID_HANDLE_VALUE)
return(false);
// Set communication parameters with SetCommState().
// Set timeouts with SetCommTimeouts().
// Set receive/transmit buffer size with SetupComm().
return(true);
}
FPort is a private data member for the Port property of TCOMPort.
This code worked fine in Windows 98. In Windows NT and XP, the
WaitCommEvent() call causes not only to suspend the thread, but also to lock
the main application until one of the specified events occurs. This means
that the application appears to hang as soon as it is started, but works
'normal' when a constant stream of data is received. I dont't understand how
a thread can lock the application that spawned it.
If I remove the WaitCommEvent() call and use polling instead, it all works
fine, but uses too much processor time for my application. Also, I don't
want to use overlapped I/O if it is not absolutely necessary.
Can anyone tell me what I'm doing wrong?
Regards,
Martin Nijhoff