东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 2477|回复: 0
打印 上一主题 下一主题

[C/C++] c++多线程构造的两种方式对比

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14441
QQ
跳转到指定楼层
楼主
发表于 2021-8-6 17:28:50 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式





c++多线程构造的两种方式对比:1、lambda函数(推荐这种,不易出错)   2、函数名与值传递




  1. #include <iostream>
  2. #include <thread>
  3. #include <string>

  4. //c++多线程构造的两种方式对比:1、lambda函数(推荐这种,不易出错)   2、函数名与值传递


  5. void add(int a, int b, int& result){
  6.     //引用是变量的别名
  7.     result = a+b;
  8. }

  9. void print_string(const std::string& s1, const std::string& s2){
  10.     std::cout << s1 << "----" << s2 << std::endl;
  11. }




  12. int main(){

  13.     int a=10,b=20;
  14.     int c,cc;
  15.     //add(a,b,c);
  16.     //std::thread t0(add, a, b, cc);   //构造线程的方式 默认只能值传递
  17.     std::thread t1(add, a, b, std::ref(cc));
  18.     //匿名函数方式
  19.     std::thread t2([a,b,&c](){
  20.         add(a,b,c);
  21.     });

  22.     //容易引起低效的问题
  23.     std::string abc("abcjowjiojeefe");
  24.     std::string def("wfefsfeaefwedef156161");
  25.     std::thread t3([&abc, &def](){
  26.         print_string(abc, def);
  27.     });

  28.     std::thread t4(print_string, abc, def);     // 效率最低  值拷贝
  29.     std::thread t5(print_string, std::ref(abc), std::ref(def));
  30.     std::thread t6(print_string, std::cref(abc), std::cref(def));  // 常引用


  31.     t1.join();
  32.     t2.join();

  33.     t3.join();
  34.     t4.join();
  35.     t5.join();
  36.     t6.join();

  37.     std::cout << "结果(匿名函数)c=" << c << std::endl;
  38.     std::cout << "结果(多参数)cc=" << cc << std::endl;

  39.    
  40.     return 0;
  41. }
复制代码


让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-5-28 15:11 , Processed in 0.188353 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表