1.编译
g++ --std=c++11 -pthread demo.cpp -o demo2.示例
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
std::mutex mtx;
std::condition_variable cv;
bool cv_ready = false;
int cnt = 0;
void worker(int id) {
std::unique_lock<std::mutex> lock(mtx); //1.lock
std::cout << "worker:" << id << " thread id:" << std::this_thread::get_id() << " is waiting...\n";
cv.wait(lock, [] { return cv_ready; }); //1.unlock 4.lock
for (int i=0; i<1000; i++){
std::this_thread::sleep_for(std::chrono::milliseconds(1));
cnt++; //处理业务 这里应该是队列 处理队列让任务出列 任务出列以后就不占用锁了
}
std::cout << "worker:" << id << " cnt:" << cnt << std::endl; //4.unlock
}
int main() {
const int thread_count = 5;
std::vector<std::thread> threads; //用向量来管理线程
for (int i = 0; i < thread_count; ++i) {
threads.emplace_back(worker, i + 1);
}
std::this_thread::sleep_for(std::chrono::seconds(3));
{
std::lock_guard<std::mutex> lock(mtx); //2.lock (这里用的是lock_guard锁不支持手动解锁)
cv_ready = true;
std::cout << "master: sets cv_ready=true.\n"; //2.unlock
}
std::cout << "master: notifies all worker.\n";
cv.notify_all(); //3.notify
for (auto& t : threads) {
t.join();
}
std::cout << "all worker have finished.\n";
return 0;
}3.输出
worker:4 thread id:140541446276864 is waiting...
worker:2 thread id:140541463062272 is waiting...
worker:5 thread id:140541437884160 is waiting...
worker:1 thread id:140541471454976 is waiting...
worker:3 thread id:140541454669568 is waiting...
master: sets cv_ready=true.
master: notifies all worker.
worker:4 cnt:1000
worker:2 cnt:2000
worker:5 cnt:3000
worker:1 cnt:4000
worker:3 cnt:5000
all worker have finished.文档更新时间: 2026-03-31 15:52 作者:morninglu
