#include
#include
#include
#include
using namespace std;
//实现两个线程交替打印,A线程打印偶数, B线程打印奇数, A线程先打印
int main()
{
mutex mtx;
int n = 100;
int i = 0;
bool flag = false;
condition_variable cv;
//本来因该打印到99结束结果打印了100是因为最后t2打印完99后i变成100,而t1进入while时i并没有到100比如是99,此时已经在while循环内了,i的值由于被t2++了由于是引用所以i就变成了100
//意思就是t1的i进入while循环之前是99卡在等锁的过程中i被t2加到了100,所以最后t1会打印100。
//t1先打印偶数
thread t1([n, &i, &mtx, &cv, &flag] {
while (i < n)
{
unique_locklock(mtx);
cv.wait(lock, [&flag]() {return !flag; });
cout << "我是A :: " << " : " << i << endl;
i++;
flag = true;
cv.notify_one();
}
});
//t2后打印奇数
thread t2([n, &i, &mtx, &cv, &flag] {
while (i < n)
{
unique_locklock(mtx);
cv.wait(lock, [&flag]() {return flag; });
cout << "我是B :: " << " : " << i << endl;
i++;
flag = false;
cv.notify_one();
}
});
t1.join();
t2.join();
system("pause");
return 0;
}