|
c++多线程构造的两种方式对比:1、lambda函数(推荐这种,不易出错) 2、函数名与值传递
- #include <iostream>
- #include <thread>
- #include <string>
- //c++多线程构造的两种方式对比:1、lambda函数(推荐这种,不易出错) 2、函数名与值传递
- void add(int a, int b, int& result){
- //引用是变量的别名
- result = a+b;
- }
- void print_string(const std::string& s1, const std::string& s2){
- std::cout << s1 << "----" << s2 << std::endl;
- }
- int main(){
- int a=10,b=20;
- int c,cc;
- //add(a,b,c);
- //std::thread t0(add, a, b, cc); //构造线程的方式 默认只能值传递
- std::thread t1(add, a, b, std::ref(cc));
- //匿名函数方式
- std::thread t2([a,b,&c](){
- add(a,b,c);
- });
- //容易引起低效的问题
- std::string abc("abcjowjiojeefe");
- std::string def("wfefsfeaefwedef156161");
- std::thread t3([&abc, &def](){
- print_string(abc, def);
- });
- std::thread t4(print_string, abc, def); // 效率最低 值拷贝
- std::thread t5(print_string, std::ref(abc), std::ref(def));
- std::thread t6(print_string, std::cref(abc), std::cref(def)); // 常引用
- t1.join();
- t2.join();
- t3.join();
- t4.join();
- t5.join();
- t6.join();
- std::cout << "结果(匿名函数)c=" << c << std::endl;
- std::cout << "结果(多参数)cc=" << cc << std::endl;
-
- return 0;
- }
复制代码
|
|