使用C++11标准的的线程语法,用两个线程轮流打印整数,一个线程打印奇数,一个线程打印偶数。可以练习线程的基本操作、线程锁和条件变量等技术。完整代码如下。代码后面附有主要语句的讲解。
#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>std::mutex data_mutex;
std::condition_variable data_var;
bool label = false;void printodd()
{std::unique_lock<std::mutex> ulock(data_mutex) ;for(int odd = 1; odd <= 100; odd += 2 ){data_var.wait(ulock,[]{return label;});std::cout<< std::this_thread::get_id() << ": " << odd <<std::endl;label = false;data_var.notify_one();}
}void printeven()
{std::unique_lock<std::mutex> ulock(data_mutex) ;for(int even = 0; even < 100; even += 2 ){std::cout<< std::this_thread::get_id() << ": " << even <<std::endl;data_var.notify_one();label = true;data_var.wait(ulock,[]{return !label;});}
}int main()
{std::thread t1(printeven);std::thread t2(printodd);t1.join();t2.join();std::cout<<"end!"<<std::endl;return 0;
}
程序中使用std::unique_lock<std::mutex> ulock(data_mutex)来管理互斥量,
这是一个RAII的资源管理方式,在ulock析构的时候,会自动释放data_mutex。
std::condition_variable提供了两种 wait() 函数。当前线程调用 wait() 后将被阻塞,此时当前线程应该获得了锁(也就是互斥量data_mutex),直到另外某个线程调用 notify_* 唤醒了当前线程。
在线程被阻塞时,该函数会自动调用 data_mutex.unlock() 释放锁,使得其他被阻塞在锁竞争上的线程得以继续执行。另外,一旦当前线程获得通知(notified,通常是另外某个线程调用 notify_* 唤醒了当前线程),wait()函数也是自动调用data_mutex.lock(),使得data_mutex的状态和 wait 函数被调用时相同。
在第二种情况下(即设置了前提条件),只有当前提条件为false时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当前提条件为true 时才会被解除阻塞。
https://blog.csdn.net/uestc_huan/article/details/53017382