0

I'm having some trouble understanding an example from Klein's serial library for C++. About halfway down this page, there is a section called "Use of Win32 synchronization objects" which I'm having trouble following. http://www.codeproject.com/Articles/992/Serial-library-for-C

// Create a handle for the overlapped operations
HANDLE hevtOverlapped = ::CreateEvent(0,TRUE,FALSE,0);;

// Open the "STOP" handle
HANDLE hevtStop = ::CreateEvent(0,TRUE,FALSE,_T("Overlapped_Stop_Event"));

// Setup the overlapped structure
OVERLAPPED ov = {0};
ov.hEvent = hevtOverlapped;

// Wait for an event
serial.WaitEvent(&ov);

// Setup array of handles in which we are interested
HANDLE ahWait[2];
ahWait[0] = hevtOverlapped;
ahWait[1] = hevtStop;

// Wait until something happens
switch (::WaitForMultipleObjects(2,ahWait,FALSE,INFINITE))
{
case WAIT_OBJECT_0:
    // Serial port event occurred
    ...

case WAIT_OBJECT_0+1:
    // Stop event raised
    ...
}

Here's what WaitEvent executes from that call (w/o all the checks and stuff):

// Wait for the COM event
::WaitCommEvent(m_hFile,LPDWORD(&m_eEvent),lpOverlapped);

::SetEvent(lpOverlapped->hEvent);

Two questions: 1) Why does he use both the WaitEvent method from his serial class and then the WaitForMultipleObjects from the Windows API right after? They seem to both do the same thing: wait for something to happen at the COM port. 2) How does the Stop event get signaled? Does WaitForMultipleObjects recognize it by name or something?

Sarkreth
  • 290
  • 2
  • 10

1 Answers1

2

This code is using overlapped I/O, that is a form of asynchronous functions, so the call to WaitCommEvent() does not actually wait for the serial event to happen, but instead it will signal the given event-object when the interesting event happens.

The WaitForMultipleObjects will wait for any of the two given event objects to become signalled:

  1. The first one will be set when WaitCommEvent() detects something interesting.
  2. The second one, there is no way in this code what will trigger it, so I'm guessing that there will be another part in the program that will signal this event, maybe by name, as you are guessing.
rodrigo
  • 94,151
  • 12
  • 143
  • 190