#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool isBFinished = false;
void threadB() {
std::cout << "B" << std::endl;
// 标记 B 线程已完成
{
std::lock_guard<std::mutex> lock(mtx);
isBFinished = true;
}
// 通知等待的线程(A线程)
cv.notify_one();
}
void threadA() {
// 等待 B 线程完成
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return isBFinished; });
}
// 输出 A
std::cout << "A" << std::endl;
}
int main() {
std::thread tB(threadB);
std::thread tA(threadA);
tB.join();
tA.join();
return 0;
}
面试高频之C++多线程顺序启动逆序执行
最新推荐文章于 2024-08-21 09:33:26 发布
1350

被折叠的 条评论
为什么被折叠?



