21xrx.com
2025-03-28 15:34:49 Friday
文章检索 我的文章 写文章
如何在 C++ 中使用多个 notify 唤醒线程?
2023-07-06 08:33:39 深夜i     69     0
C++ notify 线程 多个 使用

在 C++ 中,notify 被用来唤醒线程,被唤醒的线程被认为是处于就绪状态,并且可以继续执行。然而,有时候我们需要唤醒多个线程,这时该怎么做呢?

C++ 中有一个 condition variable(条件变量)的概念可以帮助我们解决此问题。条件变量允许在一个或多个线程等待某个特定条件时阻塞线程,并在满足条件时唤醒线程。我们可以定义多个条件变量,每个条件变量绑定到不同的条件上,并使用 notify_all 函数同时唤醒所有等待该条件的线程。

下面是一个使用多个条件变量的简单示例:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mutex1, mutex2;
std::condition_variable cv1, cv2;
bool ready1 = false, ready2 = false;
void worker1() {
  std::unique_lock<std::mutex> lock(mutex1);
  cv1.wait(lock, [] return ready1; );
  std::cout << "Worker 1 is running.\n";
}
void worker2() {
  std::unique_lock<std::mutex> lock(mutex2);
  cv2.wait(lock, [] return ready2; );
  std::cout << "Worker 2 is running.\n";
}
int main() {
  std::thread t1(worker1);
  std::thread t2(worker2);
  std::this_thread::sleep_for(std::chrono::seconds(2));
  {
    std::lock_guard<std::mutex> lock1(mutex1);
    std::lock_guard<std::mutex> lock2(mutex2);
    ready1 = true;
    ready2 = true;
  }
  cv1.notify_all();
  cv2.notify_all();
  t1.join();
  t2.join();
  return 0;
}

在此示例中,我们有两个 worker 线程(worker1 和 worker2),每个线程都绑定到一个不同的条件上。在 main 函数中,我们在两个条件变量上调用 notify_all 函数以唤醒所有等待他们的线程。

需要注意的是,在条件变量的 wait 语句中,必须使用一个 lambda 函数来定义等待状态。这个 lambda 函数将返回一个布尔值,告诉 wait 函数是否需要唤醒线程。

总之,使用条件变量和 notify_all 函数,我们可以轻松地唤醒多个线程,促进多线程编程中的协作和同步。

  
  

评论区