蓝桥ROS机器人之现代C++学习笔记7.1 并行基础

蓝桥ROS机器人之现代C++学习笔记7.1 并行基础,第1张

程序如下:

#include 
#include 

int main() {
    std::thread t([](){
        std::cout << "hello world." << std::endl;
    });
    t.join();
    return 0;
}

使用thread。

更多案例:

// thread example
#include        // std::cout
#include          // std::thread
 
void foo() 
{
  // do stuff...
}

void bar(int x)
{
  // do stuff...
}

int main() 
{
  std::thread first (foo);     // spawn new thread that calls foo()
  std::thread second (bar,0);  // spawn new thread that calls bar(0)

  std::cout << "main, foo and bar now execute concurrently...\n";

  // synchronize threads:
  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;
}

 

 

不同版本c++支持语法格式有些差异,最好用c++20

g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out

 


 

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/717874.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存