c++ - 有什么方法可以将参数传递给线程中的函数?

标签 c++ multithreading c++11

例子:

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

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

最佳答案

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

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


相反,您可以使用 constructor of 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

关于c++ - 有什么方法可以将参数传递给线程中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22443239/

相关文章:

c++ - 是否 = 在 lambda 的捕获列表中捕获 this 指针

c++ - 将带有 lambda 的 std::shared_ptr 插入 vector 中

c++ - 如何并行化将矩阵的行随机复制到内存中的另一个矩阵的过程?

c++ - 为什么我收到错误, ‘struct node’ 需要模板参数?

python - 如何正确使用 Python 中的 multiprocessing 模块?

windows - 内存映射文件是线程安全的吗

c++ - 如何在正在运行的 Visual Basic 6.0 进程(例如 MSVBVM60.DLL)中运行 Visual Basic 代码?

c++ - 什么 C+ +'s equivalent to winapi' s MsgWaitForMultipleObjectsEx

Java 同步 : Synchronization method and synchronization block

c++ - 与整数 vector 相乘并相加