🐭 std::condition_variable 与线程同步

在 C++ 多线程编程中,有时候我们需要更细粒度的控制多个线程之间的相对执行顺序,比如生产者消费者模型等。条件变量就是为了这个而引入的,主要就是通过 wait 和 notify 来实现线程同步。它可以实现多个线程之间的同步,比单纯使用锁要高效,而且代码也更加简单明了。
代码示例 :

  1. #include <condition_variable>
  2. #include <future>
  3. #include <iostream>
  4. #include <queue>
  5. #include <thread>
  6. std::deque<int> q;
  7. std::mutex mu;
  8. std::condition_variable cv;
  9. void producer() {
  10. int num = 4;
  11. while (num > 0) {
  12. std::unique_lock<std::mutex> locker(mu);
  13. q.push_front(num);
  14. locker.unlock();
  15. std::cout << "producer produces a number: " << num << std::endl;
  16. cv.notify_one(); // notify one waiting thread, if there is one
  17. std::this_thread::sleep_for(std::chrono::seconds(1));
  18. num--;
  19. }
  20. }
  21. void consumer() {
  22. int num = 0;
  23. while (num != 1) {
  24. std::unique_lock<std::mutex> locker(mu);
  25. // wait will unlock the locker when the condition is not meet
  26. // wait will lock the locker when the condition is meet later
  27. cv.wait(locker, []() { return !q.empty(); });
  28. num = q.back();
  29. q.pop_back();
  30. locker.unlock();
  31. std::cout << "consumer got a number from producer: " << num << std::endl;
  32. }
  33. }
  34. int main() {
  35. std::thread t1(producer);
  36. std::thread t2(consumer);
  37. t1.join();
  38. t2.join();
  39. return 0;
  40. }

🐂 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」堆内存的申请与释放,对性能可能会稍有影响。
代码示例 :

  1. #include <future>
  2. #include <iostream>
  3. #include <numeric>
  4. #include <vector>
  5. std::vector<int> vi(10);
  6. std::promise<void> promise{}; // This promise is used for two purposes:
  7. // 1) to synchronize accesses to vi
  8. // 2) to synchronize accesses to std::cout
  9. // use it as a shared future, and can be used in multi threads
  10. auto sharedFuture = promise.get_future().share();
  11. void producer() {
  12. std::iota(vi.begin(), vi.end(), 0);
  13. std::cout << "producer produces numbers ..." << std::endl;
  14. promise.set_value();
  15. std::this_thread::sleep_for(std::chrono::seconds(1));
  16. }
  17. void consumer() {
  18. // keeps a local copy of the shared future
  19. auto lsf = sharedFuture;
  20. lsf.wait();
  21. std::cout << "consumer get numbers from producer: " << std::endl;
  22. std::copy(vi.cbegin(), vi.cend(), std::ostream_iterator<int>(std::cout, " "));
  23. std::cout << std::endl;
  24. }
  25. int main() {
  26. std::thread t1(producer);
  27. std::thread t2(consumer);
  28. t1.join();
  29. t2.join();
  30. return 0;
  31. }

🐯 总结

  1. 正确使用 condition_variable 来进行线程同步
  2. 对于一次性事件通知的情形,可以使用 std::future 与 std::promise 来实现线程同步