Managing Multiple Threads Program Example
In the next two examples, numerous threads are created that terminate at random times. Their termination and display messages are then caught to indicate their termination status.
Multiple Threads Example
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#define NUM_THREADS 5
DWORD WINAPI thread_function(LPVOID arg)
int t_number = *(int *)arg;
wprintf(L"thread_function() is running. Arg received was %u, thread ID is %u\n", t_number, GetCurrentThreadId());
// Seed the random-number generator with
// current time so that the numbers will
// be different each time function is run.
// random time delay from 1 to 10
rand_delay = 1 + (rand() % 10);
wprintf(L"Bye from thread #%d, ID %u\n", t_number, GetCurrentThreadId());
int multiple_threads, j;
for(multiple_threads = 0; multiple_threads < NUM_THREADS; multiple_threads++)
// Create a new thread.
a_thread[multiple_threads] = CreateThread(NULL, 0, thread_function,(LPVOID)&multiple_threads, 0,NULL);
if (a_thread[multiple_threads] == NULL)
wprintf(L"CreateThread() - Thread creation failed, error %u\n", GetLastError());
wprintf(L"Waiting for threads to finish...\n");
for(multiple_threads = NUM_THREADS - 1; multiple_threads >= 0; multiple_threads--)
if (WaitForSingleObject(a_thread[multiple_threads],INFINITE) == WAIT_OBJECT_0)
wprintf(L"WaitForSingleObject() - Another thread signaled...\n");
wprintf(L"WaitForSingleObject() failed, error %u\n", GetLastError());
if(CloseHandle(a_thread[j]) != 0)
wprintf(L"a_thread[%u] handle was successfully closed!\n", j);
wprintf(L"Failed to close a_thread[%u] handle, error %u\n", j, GetLastError());
Build and run the project. The following screenshot is a sample output.
More: Synchronization Reference
The following constructs are used with synchronization in Windows. You should explore them when needed.