Win32 Synchronization

 

08 Jul 2002 16:50

WaitFor Functions

Win32 has several synchronization objects:

  1. mutex
  2. event
  3. semaphore
  4. thread handle
  5. i/o completion event

These objects are used with WaitForMultipleObjects and WaitForSingleObject.  These functions wait until an object is signaled or a timeout period expires.


Use Critical Sections


More Complex Synchronization Objects

Compound Win32 Synchronization Objects

Metered Section


Worker Threads

Context:

A worker thread that wakes up after some period of idle time and performs a background task.  The worker thread also performs operations when they are initiated by other threads.

Solution:

Use WaitForMultipleObjects or WaitForSingleObject.  An event is signaled by another thread to inform the worker thread that it needs to do something (for example:  terminate).  If no event gets set with a certain amount of time, the call to WaitFor times out, causing the worker thread to perform the idle-time task.

Solution Bugs:

The idle time processing can get starved if there are a lot of requests - the timeout period gets "reset" after each request is processed.   For example, if the idle time is 1 minute and a request comes in every 30 seconds, the idle time processing will never execute.


Waiting for a Thread to Stop

The only way to wait for a thread to stop is to call WaitForSingleObject.  Pass in the thread handle.  There is no other way to do this reliably - crashes are sure to result if another method is attempted.


Do Not Kill Threads

Killing threads can leave synchronization objects locked resulting in a corrupt application.  Use the "Worker Threads" pattern above to ask threads to stop via events.