蓝桥ROS机器人之现代C++学习笔记7.4 条件变量

Posted zhangrelay

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了蓝桥ROS机器人之现代C++学习笔记7.4 条件变量相关的知识,希望对你有一定的参考价值。

学习如下代码:

// condition_variable example
#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id (int id) 
  std::unique_lock<std::mutex> lck(mtx);
  while (!ready) cv.wait(lck);
  // ...
  std::cout << "thread " << id << '\\n';


void go() 
  std::unique_lock<std::mutex> lck(mtx);
  ready = true;
  cv.notify_all();


int main ()

  std::thread threads[10];
  // spawn 10 threads:
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(print_id,i);

  std::cout << "10 threads ready to race...\\n";
  go();                       // go!

  for (auto& th : threads) th.join();

  return 0;

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


int main() 
    std::queue<int> produced_nums;
    std::mutex mtx;
    std::condition_variable cv;
    bool notified = false;  // notification sign

    auto producer = [&]() 
        for (int i = 0; ; i++) 
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
            std::unique_lock<std::mutex> lock(mtx);
            std::cout << "producing " << i << std::endl;
            produced_nums.push(i);
            notified = true;
            cv.notify_all();
        
    ;
    auto consumer = [&]() 
        while (true) 
            std::unique_lock<std::mutex> lock(mtx);
            while (!notified)   // avoid spurious wakeup
                cv.wait(lock);
            

            // temporal unlock to allow producer produces more rather than
            // let consumer hold the lock until its consumed.
            lock.unlock();
            std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // consumer is slower
            lock.lock();
            if (!produced_nums.empty()) 
                std::cout << "consuming " << produced_nums.front() << std::endl;
                produced_nums.pop();
            
            notified = false;
        
    ;

    std::thread p(producer);
    std::thread cs[2];
    for (int i = 0; i < 2; ++i) 
        cs[i] = std::thread(consumer);
    
    p.join();
    for (int i = 0; i < 2; ++i) 
        cs[i].join();
    
    return 0;

 

 

 

 

 

 


以上是关于蓝桥ROS机器人之现代C++学习笔记7.4 条件变量的主要内容,如果未能解决你的问题,请参考以下文章

蓝桥ROS机器人之现代C++学习笔记之路径规划

蓝桥ROS机器人之现代C++学习笔记2.5 模板

蓝桥ROS机器人之现代C++学习笔记7.3 期物

蓝桥ROS机器人之现代C++学习笔记资料

蓝桥ROS机器人之现代C++学习笔记3.1 Lambda 表达式

蓝桥ROS机器人之现代C++学习笔记7.5 内存模型