c++ thread t 怎么传递参数
时间: 2023-09-03 18:12:09 浏览: 43
在 C++ 中,我们可以使用 Lambda、函数对象或函数指针来传递参数给线程。
使用 Lambda 表达式:
```c++
#include <iostream>
#include <thread>
int main() {
int num = 42;
std::thread t([&num](){
std::cout << "Thread is running with num = " << num << std::endl;
});
t.join();
return 0;
}
```
使用函数对象:
```c++
#include <iostream>
#include <thread>
class MyFunctor {
public:
MyFunctor(int &num) : m_num(num) {}
void operator()() {
std::cout << "Thread is running with num = " << m_num << std::endl;
}
private:
int &m_num;
};
int main() {
int num = 42;
MyFunctor myFunctor(num);
std::thread t(myFunctor);
t.join();
return 0;
}
```
使用函数指针:
```c++
#include <iostream>
#include <thread>
void myFunction(int &num) {
std::cout << "Thread is running with num = " << num << std::endl;
}
int main() {
int num = 42;
std::thread t(myFunction, std::ref(num));
t.join();
return 0;
}
```
注意,在使用函数指针传递参数时,如果需要传递引用类型的参数,需要使用 `std::ref` 来包装参数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)