写三个线程交替打印ABC
时间: 2023-09-21 17:04:50 浏览: 88
OK,这是一个经典的多线程问题,可以使用锁或信号量来解决。以下是一个使用锁的示例代码:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
std::condition_variable cv;
int count = 0;
void printA() {
for (int i = 0; i < 10; i++) {
std::unique_lock<std::mutex> lock(mtx);
while (count % 3 != 0) {
cv.wait(lock);
}
std::cout << "A" << std::endl;
count++;
cv.notify_all();
}
}
void printB() {
for (int i = 0; i < 10; i++) {
std::unique_lock<std::mutex> lock(mtx);
while (count % 3 != 1) {
cv.wait(lock);
}
std::cout << "B" << std::endl;
count++;
cv.notify_all();
}
}
void printC() {
for (int i = 0; i < 10; i++) {
std::unique_lock<std::mutex> lock(mtx);
while (count % 3 != 2) {
cv.wait(lock);
}
std::cout << "C" << std::endl;
count++;
cv.notify_all();
}
}
int main() {
std::thread t1(printA);
std::thread t2(printB);
std::thread t3(printC);
t1.join();
t2.join();
t3.join();
return 0;
}
希望能够帮助到你!
阅读全文