21xrx.com
2025-03-22 05:29:31 Saturday
文章检索 我的文章 写文章
C++中如何通过线程传入参数
2023-06-23 18:27:44 深夜i     21     0
C++ 线程 传入参数

在C++的多线程编程中,有时我们需要通过线程传函数所需的参数。怎样才能在创建线程时传入参数呢?以下是一些方法:

1. 通过结构体传入参数

首先,我们可以将函数的参数打包成一个结构体,然后将结构体作为线程的参数传入。这个结构体在函数中作为参数传入,就能拆包使用。

示例代码如下:

#include <iostream>
#include <thread>
using namespace std;
struct Arg
  int a;
  int b;
;
void add(Arg arg) {
  cout << arg.a + arg.b << endl;
}
int main() {
  Arg arg = 2;
  thread t(add, arg);
  t.join();
  return 0;
}

2. 通过Lambda表达式传入参数

另一种传参方法是使用Lambda表达式。Lambda表达式里可以使用外部变量。我们可以将函数要用到的参数定义在Lambda表达式的外部,然后在Lambda里面使用。

示例代码如下:

#include <iostream>
#include <thread>
using namespace std;
int main() {
  int a = 1, b = 2;
  thread t([a, b]() {
    cout << a + b << endl;
  });
  t.join();
  return 0;
}

3. 通过参数包传入多个参数

在C++11中,还可以使用变长参数模板(parameter pack)传入多个参数。参数包是一个类型安全的可变参数,它能在编译期进行类型检查和类型推导,从而避免了运行时类型错误。

示例代码如下:

#include <iostream>
#include <thread>
using namespace std;
template<typename... Args>
void add(Args... args) {
  int sum = 0;
  (..., (sum += args));
  cout << sum << endl;
}
int main() {
  int a = 1, b = 2;
  thread t(add<int, int>, a, b);
  t.join();
  return 0;
}

在大多数情况下,结构体或Lambda表达式都可以满足需求,但是在需要传递多个参数时,参数包可能会更加方便。无论使用哪种方法,线程的参数都应该被复制而不是引用。因为子线程可能会访问父线程已经销毁的变量,这样就会导致意外错误。

  
  

评论区