The Multithread without any synchronization Program 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.
// Global variable
WCHAR message = L"Hello I'm a Thread";
DWORD WINAPI thread_function(LPVOID arg)
wprintf(L"thread_function() is running. Argument received was: %s\n", arg);
for (count2 = 0; count2 < 10; count2++)
wprintf(L"The process ID is %u\n", GetCurrentProcessId());
wprintf(L"The main() thread ID is %u\n", GetCurrentThreadId());
// Create a new thread...
a_thread = CreateThread(NULL, 0, thread_function, (LPVOID)message, 0,&a_threadId);
if (a_thread == NULL)
wprintf(L"CreateThread() - Thread creation failed, error %u\n", GetLastError());
wprintf(L"CreateThread() is OK, thread ID is %u\n", a_threadId);
for (count1 = 0; count1 < 10; count1++)
wprintf(L"\n\nWaiting for thread %u to finish...\n", a_threadId);
if (WaitForSingleObject(a_thread, INFINITE) != WAIT_OBJECT_0)
wprintf(L"WaitForSingleObject() - Thread join failed! Error %u\n", GetLastError());
wprintf(L"WaitForSingleObject() is OK!\n");
// Retrieve the code returned by the thread.
if(GetExitCodeThread(a_thread, &thread_result) != 0)
wprintf(L"GetExitCodeThread() is OK! Thread joined, exit code %u\n", thread_result);
wprintf(L"GetExitCodeThread() failed, error %u\n", GetLastError());
if(CloseHandle(a_thread) != 0)
wprintf(L"a_thread handle was closed successfully!\n");
wprintf(L"Failed to close a_thread handle, error %u\n", GetLastError());
Build and run the project. The following are the sample outputs when the program was run many times.
No actual synchronization between the main thread and child thread is performed; each thread prints different characters. The sequence of the characters printed to the output may be different in each execution. Once again, it is not possible to predict the output from these examples. In most applications, unpredictable results are an undesirable feature. Consequently, it is important that you take great care in controlling access to shared resources in threaded code. There are a variety of ways to coordinate multiple threads of execution. To synchronize access to a resource, use one of the synchronization objects in one of the wait functions. The wait functions allow a thread to block its own execution. The wait functions do not return until the specified criteria have been met. A synchronization object is an object whose handle can be specified in one of the wait functions to coordinate the execution of multiple threads. More than one process can have a handle to the same synchronization object, making interprocess synchronization possible.