21xrx.com
2025-04-10 22:10:44 Thursday
文章检索 我的文章 写文章
C++实现多个条件变量
2023-07-10 12:58:38 深夜i     18     0
C++ 条件变量 多个 实现

C++是一种常用的编程语言,具有高效且强大的特性,广泛应用于软件开发领域。在多线程编程中,C++提供了一些重要的工具,例如条件变量(condition variable)。条件变量是一种同步机制,它允许一个或多个线程等待某个事件的发生,直到满足条件后才会执行。

在C++中,使用条件变量可以实现多个线程之间的同步,同时避免使用忙等(busy-waiting)的方式浪费CPU资源。在实现多个条件变量时,可以使用不同的条件变量来表示不同的事件。下面是一个简单的例子:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv1, cv2;
bool flag1 = false, flag2 = false;
void func1()
{
  // lock the mutex
  std::unique_lock<std::mutex> lck(mtx);
  // do some calculation
  std::this_thread::sleep_for(std::chrono::seconds(1));
  // set the flag to true
  flag1 = true;
  // notify the waiting thread
  cv1.notify_one();
  // wait for the other flag
  cv2.wait(lck, [] return flag2; );
  // do some work after the both flags are set
  std::cout << "Both flags are set!" << std::endl;
}
void func2()
{
  // lock the mutex
  std::unique_lock<std::mutex> lck(mtx);
  // do some calculation
  std::this_thread::sleep_for(std::chrono::seconds(2));
  // set the flag to true
  flag2 = true;
  // notify the waiting thread
  cv2.notify_one();
  // wait for the other flag
  cv1.wait(lck, [] return flag1; );
  // do some work after the both flags are set
  std::cout << "Both flags are set!" << std::endl;
}
int main()
{
  std::thread t1(func1);
  std::thread t2(func2);
  t1.join();
  t2.join();
  return 0;
}

在这个例子中,我们有两个线程(func1和func2),每个线程都有一个标志(flag1和flag2)和一个条件变量(cv1和cv2)。当一个线程完成一些工作并将其标志设置为true时,它会调用notify_one()通知等待的线程。等待的线程将使用wait()函数来等待事件的发生,并检查相应的标志以确定是否可以继续执行。

值得注意的是,wait()函数需要一个唤醒谓词(wakeup predicate),用于在线程被唤醒时检查条件是否已经满足。这个谓词需要返回一个bool值,如果返回false则当前线程将继续等待,否则它将继续执行。

总之,使用条件变量可以使多个线程之间实现同步,避免使用忙等的方式浪费CPU资源。在实现多个条件变量时,可以考虑使用不同的条件变量来表示不同的事件,以确保线程之间的正确协调。

  
  

评论区

请求出错了