#include<thread>
#include<mutex>
#include<condition_variable>
#include<iostream>
#include<vector>
std::mutex mx;
std::condition_variable cond1, cond2, cond3;
int cnt = 0;
void func1() {
while (true) {
std::unique_lock<std::mutex> lock(mx);
cond1.wait(lock, []() {return cnt == 0; });
++cnt;
std::cout << "a";
cond2.notify_one();
}
}
void func2() {
while (true) {
std::unique_lock<std::mutex> lock(mx);
cond2.wait(lock, []() {return cnt == 1; });
++cnt;
std::cout << "b";
cond3.notify_one();
}
}
void func3() {
while (true) {
std::unique_lock<std::mutex> lock(mx);
cond3.wait(lock, []() {return cnt == 2; });
cnt = 0;
std::cout << "c";
cond1.notify_one();
}
}
int main() {
std::vector<std::thread>threads;
threads.push_back(std::thread(func1));
threads.push_back(std::thread(func2));
threads.push_back(std::thread(func3));
for (int i = 0; i < threads.size(); ++i) {
if (threads[i].joinable())
threads[i].join();
}
}
多线程循环打印ABC
最新推荐文章于 2024-03-08 20:20:37 发布
2634

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



