向线程中的函数传递参数的任何方式

Any way to pass parameters to functions in a thread?

本文关键字:何方 任何方 线程 函数 参数      更新时间:2023-10-16

示例:

std::thread t1(function(8, 9));

这对我不起作用。也许有办法做到这一点。提前谢谢。

std::thread t1 (function (8, 9));

在上面的代码段中,我们将使用function(8,9)返回值初始化t1,正如您所说,这不是您想要的。


相反,您可以使用std::thread的构造函数,该构造函数定义为将可调用对象作为其第一个参数,而不是在调用它时应传递给它的参数。

std::thread t1 (function, 8, 9);

看看这个简单的例子:

#include <iostream>
#include <thread>
void func (int a, float b) {
  std::cout << "a: " << a << "n";
  std::cout << "b: " << b << "n";
}
int main () {
  std::thread t1 (func, 123, 3.14f);
  t1.join ();
}

a: 123
b: 3.14