如何在thread中加参数c++
时间: 2023-08-17 09:05:21 浏览: 43
在 C++ 中,可以使用以下两种方法在线程中传递参数:
1. 传递指针
可以通过传递指向参数的指针来在线程中传递参数。例如:
```c++
#include <iostream>
#include <thread>
void foo(int* x) {
std::cout << "Value of x: " << *x << std::endl;
(*x)++;
}
int main() {
int x = 5;
std::thread t(foo, &x);
t.join();
std::cout << "Updated value of x: " << x << std::endl;
return 0;
}
```
在上面的例子中,参数 x 是通过传递一个指向 x 的指针来传递的。在线程函数 foo 中,可以通过解引用指针来访问参数的值。
2. 使用 std::ref
另一种方法是使用 std::ref 函数来传递引用作为参数。例如:
```c++
#include <iostream>
#include <thread>
void foo(int& x) {
std::cout << "Value of x: " << x << std::endl;
x++;
}
int main() {
int x = 5;
std::thread t(foo, std::ref(x));
t.join();
std::cout << "Updated value of x: " << x << std::endl;
return 0;
}
```
在上面的例子中,参数 x 是通过传递一个引用来传递的。在调用线程函数时,使用 std::ref 函数将 x 包装在一个 std::reference_wrapper 对象中,以便将其传递给线程函数 foo。在线程函数中,可以像使用引用一样使用参数 x。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)