c++ - 'std::thread' 如何确定传递给构造函数的可变参数的数量

标签 c++ multithreading variadic-functions

当调用 std::thread 的构造函数时,您传递一个函数及其所需的参数。 std::thread 如何确定要传递给函数的参数总数?

#include <iostream>
#include <thread>

void task(int i, char c, bool b)
{
    return;
}

int main(int argc, char** argv)
{
    std::thread t(task, 10, 'c', true); // these 3 arguments
    t.join();
}

最佳答案

std::thread constructor是使用 variadic template 实现的:

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

地点:

  • Function是将由线程调用的可调用对象的类型(无论是函数、lambda、仿函数等)。
  • Argsargs 中的类型列表可变参数。
  • f是线程将调用的实际可调用对象。
  • args是将传递给 f 的值列表.

std::thread然后就可以转发argsf使用参数包扩展类似于 f(args...); 。编译器本身,而不是 std::thread ,将展开args...到实际值,即:f(arg1, arg2, ..., argN) .

所以,std::thread t(task, 10, 'c', true);将创建一个工作线程来进行类似于 f(args...) 的调用,这将被扩展为 task(10, 'c', true) .

因此,您传递给 std::thread 的参数构造函数必须与 f 的参数匹配callable 传入,否则代码无法编译。

关于c++ - 'std::thread' 如何确定传递给构造函数的可变参数的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64235651/

相关文章:

c++ - C/C++ 当 select 挂起时将套接字添加到 fd_set

python - Flask session 变量是否跨线程维护状态?

c++ - 最优雅的可变函数

c++ - 我应该使用哪些编译标志来避免运行时错误

java - 当我尝试中断线程时 JFrame 卡住

cocoa - 接受输入作为参数数量可变的 block 的方法声明中出现编译错误

c++ - Valgrind 条件跳转或移动取决于使用可变参数函数的链式调用时未初始化的值

c++ - 在STL映射中通过引用查找并返回

C++ 比较整数与硬编码整数集的更简单方法

c++ - 零可变宏参数的 GCC 编译器警告标志