2.用两个线程实现ABABABAB....打印10次。
时间: 2024-05-03 10:20:20 浏览: 9
好的,这是一个比较经典的多线程面试题。解决方案可以使用两个线程分别打印字母 A 和 B,使用一个计数器来判断打印了多少次,并使用互斥量来保证线程间的同步。具体实现细节可以参考下面的代码示例:
```c++
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
int count = 0;
void printA()
{
while (count < 10)
{
mtx.lock();
if (count < 10)
{
cout << "A";
count++;
}
mtx.unlock();
}
}
void printB()
{
while (count < 10)
{
mtx.lock();
if (count < 10)
{
cout << "B";
count++;
}
mtx.unlock();
}
}
int main()
{
thread t1(printA);
thread t2(printB);
t1.join();
t2.join();
return 0;
}
```
这里使用了一个全局计数器和互斥量 mtx 来实现线程的同步。在 printA 和 printB 函数中,首先通过 lock 函数锁住互斥量 mtx,然后检查计数器 count 是否达到了目标值 10,如果没有,则输出相应的字符,并将计数器加一。最后通过 unlock 函数解锁互斥量 mtx,释放锁供其他线程使用。
注意,在 printA 和 printB 函数中需要使用 while 循环来不断判断计数器的值,否则可能会出现线程过早退出的情况。另外,在 main 函数中需要通过 join 函数等待两个线程的执行完毕,否则可能会出现程序提前结束的情况。