c++中wait的用法是什么

avatar
作者
筋斗云
阅读量:0

在C++中,wait通常用于线程同步机制中,用于使当前线程进入等待状态,直到条件满足或者被通知后才继续执行。wait通常与mutexcondition_variable一起使用。具体用法如下:

  1. 使用std::unique_lock对象对mutex进行加锁。
  2. 调用condition_variable对象的wait方法,将unique_lock对象传入,使当前线程进入等待状态。
  3. 在另一个线程中满足某个条件时,调用condition_variable对象的notify_onenotify_all方法,通知等待的线程。
  4. 等待的线程被通知后,wait方法返回,继续执行。

示例代码如下:

#include  #include  #include  #include   std::mutex mtx; std::condition_variable cv; bool ready = false;  void wait_func() {     std::unique_lock lck(mtx);     while (!ready) {         cv.wait(lck);     }     std::cout << "Thread is notified." << std::endl; }  void notify_func() {     std::this_thread::sleep_for(std::chrono::seconds(2));     {         std::lock_guard lck(mtx);         ready = true;     }     cv.notify_one(); }  int main() {     std::thread t1(wait_func);     std::thread t2(notify_func);          t1.join();     t2.join();          return 0; } 

在上面的示例中,wait_func线程等待ready状态变为truenotify_func线程在2秒后将ready状态设置为true并通知等待的线程。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!