WaitForMultipleObjects

This short program demonstrates how to use the call WaitForMultipleObjects to wait for threads to finish.  Here is MSDN Online's description of WaitForMultipleObjects.

This program creates three threads that run for 1 second, 2 seconds, and 3 seconds.  The main thread waits for all of these threads to finish before it exits. Here are the MSVC++ project and executable for this program.

The output of the below program is:

SleepThread(2000) sleeping for 2000 ms
SleepThread(3000) sleeping for 3000 ms
SleepThread(1000) sleeping for 1000 ms
SleepThread(1000) exiting
SleepThread(2000) exiting
SleepThread(3000) exiting
All threads have exited.  Press Enter to continue.

waitThread.cpp:

#include <windows.h>
#include <stdio.h>
#include <assert.h>

//
// Sleep for the specified milliseconds and then exit
//
unsigned long __stdcall
SleepThread( void * msToWait )
{
    int ms = (int)msToWait;

    printf( "SleepThread(%d) sleeping for %d ms\n", ms, ms );
    Sleep( ms );
    printf( "SleepThread(%d) exiting\n", ms );

    return 0;
}


//
// Main
//
void
main()
{
    DWORD threadID;
    DWORD retVal;
    HANDLE threadHandles[3];
    
    //
    // Create three threads that Sleep 1, 2, and 3 seconds
    //
    threadHandles[0] = CreateThread( NULL, 0, SleepThread, (void*)1000, 0, &threadID );
    assert( threadHandles[0] != NULL );  // always check for success

    threadHandles[1] = CreateThread( NULL, 0, SleepThread, (void*)2000, 0, &threadID );
    assert( threadHandles[1] != NULL );  // always check for success

    threadHandles[2] = CreateThread( NULL, 0, SleepThread, (void*)3000, 0, &threadID );
    assert( threadHandles[2] != NULL );  // always check for success

    //
    // WaitForMultipleObjects can accept at most MAXIMUM_WAIT_OBJECTS objects.
    //
    int numThreads = 3;
    assert( numThreads <= MAXIMUM_WAIT_OBJECTS );

    //
    // Wait for the three threads to finish
    //
    retVal = WaitForMultipleObjects( numThreads,    // number of threads to wait for 
                                     threadHandles, // handles for threads to wait for
                                     TRUE,          // wait for all of the threads
                                     INFINITE       // wait forever
                                    );

    //
    // If successful, WaitForMultipleObjects returns a value between
    // WAIT_OBJECT_0 and ( WAIT_OBJECT_0 + numThreads - 1).  
    //
    // This assert checks if the function was successful.
    //
    assert( ( retVal >= WAIT_OBJECT_0 ) && ( retVal <= ( WAIT_OBJECT_0 + numThreads - 1 ) ) );

    printf( "All threads have exited.\n" );
    Sleep( 1000 );
}