// condition.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <mutex> #include <thread> #include <condition_variable> #include <Windows.h> #include <time.h> #include <chrono> using namespace std; mutex g_mtx; mutex ExitMtx; timed_mutex timemtx; int data[2000] = { 0 }; int pos = 0; int max = 0; condition_variable cv; HANDLE g_mtxHandle = nullptr; bool ExitFlag = false; // display void display() { int cnt = 0; while (cnt++ < 200) { if (timemtx.try_lock_for(chrono::milliseconds(2000))) { cout << "display: " << data[cnt] << endl; Sleep(500); timemtx.unlock(); } else { cout << "display time out ......." << endl; } } } // consumer void Consumer(){ int cnt = 0; int postion = 0; while (cnt++ < 20) { Sleep(2000); if (timemtx.try_lock_for(chrono::milliseconds(2000))) { for (int i = 0; i < 10; ++i) { data[postion++] = max++; cout << "Consumer max: " << max << endl; } timemtx.unlock(); } else { cout << "Consumer time out ......." << endl; } if (cnt == 10) { ExitFlag = true; cv.notify_one(); return; } } } int _tmain(int argc, _TCHAR* argv[]) { thread t1 = thread(Consumer); thread t2 = thread(display); std::unique_lock<std::mutex> lk(ExitMtx); //cv.wait(lk, []{return ExitFlag; }); if (cv.wait_for(lk, chrono::seconds(1)) == std::cv_status::no_timeout) { cout << "waited ExitFlag....." << endl; } else{ cout << "waited ExitFlag time out....." << endl; } t1.join(); t2.join(); return 0; }