C++条件变量condition_variable

#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>

std::mutex mutex;
std::condition_variable cond;

void in_msg()
{
   while(true)
   {
      std::chrono::milliseconds second(1000);
      std::this_thread::sleep_for(second);

      std::unique_lock<std::mutex> unique(mutex);      
      cond.notify_one();
   }
}

void out_msg()
{
   while(true)
   {
      std::unique_lock<std::mutex> unique(mutex);      
      cond.wait(unique);

      unique.unlock(); //可以提前解锁
      std::cout << "out_msg" << std::endl;
   }
}

int main()
{
   std::thread inthread(&in_msg);
   std::thread outthread(&out_msg);
   inthread.join();
   outthread.join();

   return 0;
}
$ g++ msg_queue.cpp -std=c++11 -pthread
$ ./a.out                              
out_msg
out_msg
posted @ 2022-08-07 22:12  thomas_blog  阅读(38)  评论(0编辑  收藏  举报