[c++11]條件變數測試2
阿新 • • 發佈:2018-11-27
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
std::mutex global_mutex;
std::condition_variable global_cv;
bool is_avaliable = false;
void cv_thread()
{
int cnt = 0;
std::unique_lock<std::mutex> lock(global_mutex);
std::cout << "cv_thread, before loop, is locked = " << lock.owns_lock() << std::endl;
while (is_avaliable == false)
{
global_cv.wait(lock);
std::cout << "cv_thread, in loop, is locked = " << lock.owns_lock();
std::cout << " cnt = " << cnt << std::endl;
++cnt;
if (cnt == 10)
{
break;
}
}
}
int main()
{
std::thread cv_work(cv_thread);
std::this_thread::sleep_for(std::chrono::seconds(1));
std::unique_lock< std::mutex> lock(global_mutex);
std::cout << "lock in main, is locked = " << lock.owns_lock() << std::endl;
for (int i = 0; i < 10; ++i)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "send notify : " << i << std::endl;
}
lock.unlock();
cv_work.join();
return 0;
}
輸出結果:
cv_thread, before loop, is locked = 1
lock in main, is locked = 1
send notify : 0
send notify : 1
send notify : 2
send notify : 3
send notify : 4
send notify : 5
send notify : 6
send notify : 7
send notify : 8
send notify : 9