std::thread 传参
时间: 2023-11-23 16:52:55 浏览: 44
std::thread可以通过向构造函数传递额外的参数来向线程函数传递参数。具体来说,可以将参数依次传递给std::thread构造函数,例如std::thread t(hello,arg1,arg2),其中hello是线程函数,arg1和arg2是传递给线程函数的参数。另外,也可以提前将参数转化为需要的类型,然后再传递给std::thread构造函数,例如std::thread t(f,3,std::string(buffer)),其中f是线程函数,3和std::string(buffer)是传递给线程函数的参数。需要注意的是,std::thread的所有权机制跟std::unique_ptr一样,不能拷贝,但可以转移所有权。
相关问题
std::thread传参
std::thread传参可以通过以下两种方式实现:
1. 通过传递参数的方式:
可以使用lambda表达式或者函数指针作为std::thread的参数,将需要传递的参数作为lambda表达式或者函数指针的参数传递进去即可。
例如:
void func(int a, int b) {
// do something
}
int main() {
int a = 1, b = 2;
std::thread t(func, a, b);
t.join();
return 0;
}
2. 通过传递引用的方式:
可以使用std::ref()将需要传递的参数包装成引用,然后将引用作为std::thread的参数传递进去即可。
例如:
void func(int& a, int& b) {
// do something
}
int main() {
int a = 1, b = 2;
std::thread t(func, std::ref(a), std::ref(b));
t.join();
return 0;
}
函数想传参怎么改写:std::shared_ptr<std::thread> get_thread_; get_thread_ = std::make_shared<std::thread>(&HTTPClient::get_list, this); if (get_thread_->joinable()) { get_thread_->join(); }
如果需要传递参数给get_list函数,可以在std::make_shared函数中添加参数,这些参数将被传递给get_list函数。例如,如果需要将整数1和字符串"example"传递给get_list函数,可以将代码修改为:
```
std::shared_ptr<std::thread> get_thread_;
get_thread_ = std::make_shared<std::thread>(&HTTPClient::get_list, this, 1, "example");
if (get_thread_->joinable()) {
get_thread_->join();
}
```
这里的1和"example"将作为额外的参数传递给get_list函数。需要注意的是,这些参数的类型必须与get_list函数的参数类型匹配。例如,如果get_list函数的参数类型是int和const std::string&,那么传递给std::make_shared函数的参数类型也应该是int和const std::string&。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)