通过互斥锁和条件变量实现线程同步
例题:交替打印ABCDEABCDE…
代码:
#include <iostream>
#include <future>
#include <thread>
#include <unistd.h>
#include <mutex>
using namespace std;
mutex mx; //互斥锁
condition_variable cv; //条件变量
int flag = 0;//全局变量,理解为全局的一个状态
int NUM = 5;//线程数量,5表示打印ABCDE
//线程打印函数
void foo(const int i)
{
while(1)
{
unique_lock<mutex> lk(mx);
//while(i != flag % NUM) cv.wait(lk);
cv.wait(lck, [a](){
return i == flag % NUM;
});
++flag;
cv.notify_all();
cout << "------ " << static_cast<char>('A' + i)<< endl;
}
}
int main()
{
vector<thread> tds(NUM);
cout << "now start:" << endl;
for (int i = 0; i < NUM; ++i)
{
tds[i] = thread(foo, i);
}
for_each(vs.begin(), vs.end(), mem_fn(&thread::join));
return 0;
}