/////////////////////////////////////////////////////////////// // Concurrency.cpp - illustration of concurrent activities // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2013 // /////////////////////////////////////////////////////////////// #include #include #include #include #include #include void Title(const std::string& title) { std::cout << "\n " << title.c_str(); std::cout << "\n " << std::string(title.size() + 2, '=').c_str(); std::cout.flush(); } void threadProc(std::string& shared, std::string id, size_t sleepTime) { static std::mutex mtx; for(int i=0; i<10; ++i) { mtx.lock(); shared += id; mtx.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); } } int main() { Title("Concurrency"); std::string shared; std::thread t1(threadProc, std::ref(shared), "1", 100); std::thread t2(threadProc, std::ref(shared), "2", 200); std::thread t3(threadProc, std::ref(shared), "3", 100); //t1.join(); //t2.join(); //t3.join(); HANDLE handle[3]; handle[0] = t1.native_handle(); handle[1] = t2.native_handle(); handle[2] = t3.native_handle(); ::WaitForMultipleObjects(3, handle, true, INFINITE); t1.detach(); t2.detach(); t3.detach(); std::cout << "\n " << shared.c_str() << "\n\n"; return 0; }