std::condition_variable 练习(多线程任务序列化)
#include <functional> #include <map> #include <random> #include <chrono> #include <iostream> #include <format> #include <cmath> #include <thread> #include <future> struct{ std::condition_variable cv; std::mutex mutex; int flag{}; bool start{}; }g_var; void thead_sequence_run(int id) { std::cout << "thread[" << id << "] ready\n"; std::unique_lock lk(g_var.mutex); //由于RAII机制(资源获取即初始化),lk处于lock状态(unique_lock构造方法中调用了mutex.lock) g_var.cv.wait(lk, [id]()->bool {return g_var.flag == id; }); //如果被阻塞, cv会自动执行lk.unlock() std::cout << "thread[" << id << "] begin\n"; std::random_device rd; std::mt19937 engine(rd()); std::uniform_int_distribution dis(0, 300); std::this_thread::sleep_for(std::chrono::milliseconds(dis(engine))); std::cout << "thread[" << id << "] finish\n"; ++g_var.flag ; g_var.cv.notify_all(); } int main() { using namespace std::chrono_literals; int t_cnt = 30; std::vector<std::thread> vec_threads; for (int i = 0; i < t_cnt; i++) { vec_threads.emplace_back(thead_sequence_run, i+1); } ++g_var.flag; g_var.cv.notify_all(); for (auto& t : vec_threads) { t.join(); } std::cout << "g.flag=" << g_var.flag << std::endl; }