c++ thread 如何传递多个参数
时间: 2023-07-04 07:22:50 浏览: 87
在 C++ 的 std::thread 中,可以使用 std::tuple 来传递多个参数。具体实现步骤如下:
1. 定义一个函数,该函数的参数为 std::tuple 类型。
2. 将多个参数打包成 std::tuple 类型。
3. 在创建 std::thread 对象时,将打包后的 std::tuple 类型作为参数传入。
示例代码如下:
```
#include <iostream>
#include <thread>
#include <tuple>
void thread_func(std::tuple<int, float, std::string> args)
{
int param1 = std::get<0>(args);
float param2 = std::get<1>(args);
std::string param3 = std::get<2>(args);
std::cout << "param1: " << param1 << std::endl;
std::cout << "param2: " << param2 << std::endl;
std::cout << "param3: " << param3 << std::endl;
}
int main()
{
int param1 = 10;
float param2 = 3.14f;
std::string param3 = "hello world";
std::tuple<int, float, std::string> args(param1, param2, param3);
std::thread t(thread_func, args);
t.join();
return 0;
}
```
在上面的示例代码中,我们定义了一个名为 `thread_func` 的函数,该函数的参数为 `std::tuple<int, float, std::string>` 类型。在 `main` 函数中,我们将多个参数打包成一个 `std::tuple` 类型,然后将该类型作为参数传入 `std::thread` 对象的构造函数中。在 `thread_func` 函数中,我们使用 `std::get` 函数来获取参数的值,并打印出来。