C++11子线程参数引用,实际进行的是值传递

C++11多线程中引用传递参数时,不能直接写变量,因为这实际上进行的是值传递,尽管你在定义函数时使用了&来希望是引用传递。

通常,线程中引用传递有两种方法:

 std::ref(s);

 std::move(s); // 不建议,因为运行后,该对象S会在后面就无法使用了

注意:线程在创建时,既可以传递函数,也可以传递仿函数(Functor),但在传递仿函数functor时,要注意传参时,应传: (functor()).

复制代码
 1 #ifndef MAIN_CPP
 2 #include<iostream>
 3 #include<thread>
 4 #include<stdlib.h>  //EXIT_SUCCESS
 5 #include <stdio.h> // system(“pause”);
 6 #include<string>
 7 #include "factor.h"
 8 using  namespace std;
 9 void func();
10 void factor01::operator()(const string& s) {
11     func();
12     cout << "print s=" <<s<< endl;
13 }
14 void func() {
15  
16     cout << "www.baidu.com" << endl;
17 }
18 int main() {
19     factor01 f1;
20     //thread t1(f1);
21     //thread t1((factor01()));
22     const string s="I love China!";
23     thread t2((factor01()), std::move(s));  // 引用传递给线程时,有两种方法:1)std::ref(s) 2) std::move(s) -> in POIX, 引用必须用以上进行传参,否则就是值传递。
24  
25     try {
26          
27     }
28     catch (...)//all exceptions
29     {
30         t2.join();
31         throw;
32     }
33     //t1.join();
34     if(t2.joinable())
35         t2.join();
36     system("pause");
37     return  EXIT_SUCCESS;
38 }
39  
40 #endif // !1
复制代码

 

posted @   飞猪流  阅读(135)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示