Listing 2 Thread synchronization using mutex variables
#include <windows.h> #include <iostream> HANDLE mutex; void thread_entry () { WaitForSingleObject ( mutex, INFINITE ); for ( int i = 10; i > 0; --i ) { Sleep ( 200 ); std::cout << "world" << std::endl; } ReleaseMutex ( mutex ); } int main () { mutex = CreateMutex ( 0, NULL, 0 ); HANDLE thread = CreateThread ( NULL, 0, ( LPTHREAD_START_ROUTINE ) thread_entry, NULL, 0, NULL ); WaitForSingleObject ( mutex, INFINITE ); for ( int i = 10; i > 0; --i ) { Sleep ( 100 ); std::cout << "hello" << std::endl; } ReleaseMutex ( mutex ); WaitForSingleObject ( thread, INFINITE ); return ( 0 ); }