#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
bool use_cv = false;
void do_print_id(int id)
{
bool test = true;
std::cout << "thread begin " << id << std::endl;
if (use_cv) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) { // 如果不为true 则等待
if (test) {
std::cout << "begin to wait_for" << std::endl;
// cv.wait(lck); // 当前线程被阻塞 当全局标志为true后 线程被唤醒
auto r = cv.wait_for(lck, std::chrono::milliseconds(1000)); // 需要根据wait_for返回值 是条件满足还是超时
if (r == std::cv_status::timeout) {
std::cout << "cv_status::timeout." << std::endl;
} else {
std::cout << "cv_status::no_timeout." << std::endl;
}
} else {
std::cout << "thread " << id << " test sleep." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
test = true;
}
}
} else {
// std::unique_lock<std::mutex> lck(mtx);
// 如果在此处定义[std::unique_lock<std::mutex> lck(mtx);] 则第一个启动的线程则会一直在while中持有锁, 不释放;
// 后面创建的线程 无法进入while循环
while (!ready) { // 如果不为true 则等待
std::cout << "thread " << id << " wait." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
std::cout << "thread " << id << " End."<< std::endl;
}
void go()
{
if (use_cv) {
std::unique_lock<std::mutex> lck(mtx);
ready = true; // 设置全局标志为true
cv.notify_all(); // 唤醒所有线程
} else {
ready = true; // 设置全局标志为true
}
}
int main()
{
const int thread_size = 1;
use_cv = true;
std::thread threads[thread_size];
for (int i = 0; i < thread_size; i++)
threads[i] = std::thread(do_print_id, i);
#if 1
for (auto& th:threads)
th.detach();
#else
for (auto& th:threads)
th.join(); // 如果使用join则会卡住 是因为10个线程都没有完全退出while
#endif
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
std::cout << "10 threads ready to race ... " << std::endl;
go();
while (1) {
std::cout << "Main Loop" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}