/////////////////////////////////////////////////////////////////////// // PlatformThreads.cpp - Demonstrate Basic Windows Thread Operations // // // // Jim Fawcett, CSE687-OnLine, Object Oriented Design, Fall 2017 // /////////////////////////////////////////////////////////////////////// #include // _beginthreadex #include // HANDLE, CreateMutex, WaitForSingleObject, ... #include unsigned int __stdcall threadProc(void* params) { // static so mutex will only be created once static HANDLE hMutex = CreateMutex(nullptr, false, nullptr); for (size_t i = 0; i < 5; ++i) { // lock output so all three insertions happen on same thread WaitForSingleObject(hMutex, INFINITE); long int id = ::GetCurrentThreadId(); std::cout << "\n pass #" << i << ", running on thread " << id; ReleaseMutex(hMutex); // sleep for irregular intervals to cause interleaving ::Sleep(id/100); } return 0; } HANDLE CreateChildThread() { return (HANDLE)_beginthreadex(nullptr, 0, threadProc, nullptr, 0, nullptr); } int main() { std::cout << "\n Demonstrate Basic Platform Thread Operations"; std::cout << "\n =============================================="; HANDLE hThrd1 = CreateChildThread(); HANDLE hThrd2 = CreateChildThread(); HANDLE hThrd3 = CreateChildThread(); WaitForSingleObject(hThrd1, INFINITE); WaitForSingleObject(hThrd2, INFINITE); WaitForSingleObject(hThrd3, INFINITE); std::cout << "\n\n"; return 0; }