问题:创建三个线程,每个线程分别打印A、B、C各十次。但是要保证打印顺序为ABCABC…
#include
std::mutex mtx;//锁
std::condition_variable cv; //条件变量
char arr[]={‘A’, ‘B’, ‘C’};
char message = ‘A’;
打印函数:
void Print(int i)
{
for (int j = 0; j<10; ++j)
{
std::unique_lock<std::mutex> lock(mtx);
//必须使用std::unique_lock而不能使用std::shared_lock,
//因为在cvwait时会解锁,涉及到额外的加锁、解锁就需要用unique
cv.wait(lock,[&]{
return message == arr[i];
});
std::cout<<arr[i]<<" "<<std::endl;
message = arr[(i+1)%3];
lock.unlock();//可以不加,因为函数执行完成后会自动解锁
cv.notify_all();
//必须使用notify_all而不能使用notify_one,因为需要唤醒所有线程去判断是否轮到当前线程打印。
}
}
创建线程:
std::thread t[3];//创建三个线程
for (auto i=0; i<3;i++)
{
//调用的函数原型为:
/* template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);*/
t[i]=std::thread(Print,i);
}
for (auto i=0; i<3;i++)
{
//阻塞等待线程执行完毕
t[i].join();
//如果不调用join,因为马上执行线程的析构函数,则会死机,如下:
/*If the thread is joinable when destroyed, terminate() is called.*/
//而线程创建之后,默认是joinable
}