c++ 条件变量

//
// Created by wuyongyu on 2019-10-10.
//

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std::chrono_literals; // for sleep_for(10s)
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void worker_thread()
{
  // Wait until main() sends data
  std::unique_lock lk(m);
  std::cout << "work_thread id:" << std::this_thread::get_id() << std::endl;
  // condition_vadiable will block this thread
   cv.wait(lk, []{
     std::cout << "wait ready:" << ready << std::endl;
     return ready;});

  // after the wait, we own the lock.
  std::cout << "Worker thread is processing data\n";
  data += " after processing";

  // Send data back to main()
  processed = true;
  std::cout << "Worker thread signals data processing completed\n";

  // Manual unlocking is done before notifying, to avoid waking up
  // the waiting thread only to block again (see notify_one for details)
  lk.unlock();
  // sleep 5s ,then notify the thread
  std::this_thread::sleep_for(5s);
  cv.notify_one();
}

int main()
{

  data = "Example data";
  // send data to the worker thread
  {
    // std::lock_guard lk(m);
    std::unique_lock lock(m);
    ready = true;
    std::cout << "main() signals data ready for processing\n";
    lock.unlock();
  }
  std::thread worker(worker_thread);

  // sleep 5s ,then notify the thread
  std::this_thread::sleep_for(5s);
  cv.notify_one();
  // wait for the worker
  {
    std::unique_lock lk(m);
    cv.wait(lk, []{return processed;});
    std::cout << "main() get process " << std::endl;
    lk.unlock();
  }
  std::cout << "Back in main(), data = " << data << '\n';
  worker.join();
  return 0;
}

你可能感兴趣的:(c-c++)