Thread Synchronisation

All synchronization in Win32 applications is via cooperative waiting. To wait on a Win32 object, an open handle to the object with ‘synchronize’ access is required. WaitForSingleObject() will then wait for any appropriate object to become signaled.

The Event, Mutex and Semaphore objects we are about to discuss are specifically designed for the purpose of arbitrating access or serializing operation. However, other types of Win32 object can be waited on. For instance, a Win32 thread object is unsignalled for the whole of its lifetime and becomes signaled when it terminates. So you could wait for a thread to die by waiting for it to become signaled. A Win32 file object is signaled when an outstanding I/O request on it is completed. So you could perform asynchronous I/O on a file by issuing an I/O request and waiting on its handle for it to become signaled. There are good reasons, discussed later, why you would not want to do this.

A timeout period can be specified, in ins, as the maximum time WaitForSingleObject() will wait for the object before returning.

If an object is not signaled, the function blocks until another thread signals it, or the timeout elapses. A timeout value of INFINITE will wait indefinitely.

A timeout value of 0 causes WaitForSingleObject() to return immediately, even if the object is not signaled. This is useful if you want a thread to do something while it is waiting for clearance. It will cause the calling thread to lose the rest of its time slice.

If the state of the object is signaled, or becomes signaled before the time period elapses, the function returns WAIT_OBJECT_0 and the thread can resume execution.

If the timeout elapses before the object is signaled, the function returns WAIT_TIMEOUT. WaitForMultipleObjects() waits for a multiple number of objects, potentially of different types. For instance, you might wait for a thread to terminate and for a Mutex to be unowned. An array of object handles is specified, and another parameter dictates whether all objects need to be signaled before the function returns, or whether the signaling of any one object will satisfy. Again, a timeout period can be specified with mostly the same operation as above. If it is waiting for only one of many objects to become signaled, the function returns (WAIT OBJECT_0 + index) , where index is the array item that satisfied the wait. If several objects in the array are signaled, the object with the lowest array index is returned.

previous page next page