🐭 std::condition_variable 与线程同步
在 C++ 多线程编程中,有时候我们需要更细粒度的控制多个线程之间的相对执行顺序,比如生产者消费者模型等。条件变量就是为了这个而引入的,主要就是通过 wait 和 notify 来实现线程同步。它可以实现多个线程之间的同步,比单纯使用锁要高效,而且代码也更加简单明了。
代码示例 :
#include <condition_variable>#include <future>#include <iostream>#include <queue>#include <thread>std::deque<int> q;std::mutex mu;std::condition_variable cv;void producer() {int num = 4;while (num > 0) {std::unique_lock<std::mutex> locker(mu);q.push_front(num);locker.unlock();std::cout << "producer produces a number: " << num << std::endl;cv.notify_one(); // notify one waiting thread, if there is onestd::this_thread::sleep_for(std::chrono::seconds(1));num--;}}void consumer() {int num = 0;while (num != 1) {std::unique_lock<std::mutex> locker(mu);// wait will unlock the locker when the condition is not meet// wait will lock the locker when the condition is meet latercv.wait(locker, []() { return !q.empty(); });num = q.back();q.pop_back();locker.unlock();std::cout << "consumer got a number from producer: " << num << std::endl;}}int main() {std::thread t1(producer);std::thread t2(consumer);t1.join();t2.join();return 0;}
🐂 std::promise 与一次性事件通知
使用 std::condition_variable 来实现线程之间的同步,是标准推荐的使用方式,我们也可以使用锁的方式来实现,另外,使用原子变量结合内存模型也可以实现线程同步。
我们之前说过 std::future 与 std::promise 之间也是可以进行同步通讯的,类似于一个 channel, 一端 std::promise 负责写入,另一端 std::future 负责读取,写入操作会阻塞读取操作,这个刚好可以用来同步两个线程,使用 std::shared_future 可以同步多个主从线程。但是 std::promise 只能写入一次,因此,对于那种只需要一次性通知的同步事件,我们可以使用 std::future 与 std::promise 来实现线程同步。但是,这个会涉及到对 「shared state」堆内存的申请与释放,对性能可能会稍有影响。
代码示例 :
#include <future>#include <iostream>#include <numeric>#include <vector>std::vector<int> vi(10);std::promise<void> promise{}; // This promise is used for two purposes:// 1) to synchronize accesses to vi// 2) to synchronize accesses to std::cout// use it as a shared future, and can be used in multi threadsauto sharedFuture = promise.get_future().share();void producer() {std::iota(vi.begin(), vi.end(), 0);std::cout << "producer produces numbers ..." << std::endl;promise.set_value();std::this_thread::sleep_for(std::chrono::seconds(1));}void consumer() {// keeps a local copy of the shared futureauto lsf = sharedFuture;lsf.wait();std::cout << "consumer get numbers from producer: " << std::endl;std::copy(vi.cbegin(), vi.cend(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;}int main() {std::thread t1(producer);std::thread t2(consumer);t1.join();t2.join();return 0;}
🐯 总结
- 正确使用 condition_variable 来进行线程同步
- 对于一次性事件通知的情形,可以使用 std::future 与 std::promise
来实现线程同步
