当调用 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、仿函数等)。 -
Args
是args
中的类型列表可变参数。 -
f
是线程将调用的实际可调用对象。 -
args
是将传递给f
的值列表.
std::thread
然后就可以转发args
至f
使用参数包扩展,类似于 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/