[英]Does std thread constructor take variadic thread function?
I am trying to pass a variable count of callback functions (all of the same signature) to a thread function.我正在尝试将可变计数的回调函数(所有相同的签名)传递给线程 function。 I came up with the following code我想出了以下代码
using namespace std;
void callback(int i)
{
cout<<"thread "<<i<<" running"<<endl;
}
template<typename ...CallbackType>
void threadProc(int id, CallbackType ...callbackPack)
{
auto callbacks = {callbackPack...};
for(auto callback : callbacks)
{
callback(id);
}
}
int main()
{
thread t(threadProc<void(int)>, 1, callback);
t.join();
return 0;
}
This code fails to compile with此代码无法编译
error: no matching function for call to ‘std::thread::thread(, int, void (&)(int))’
thread t(threadProc<void(int)>, 1, callback);
Things would work fine if threadProc()
is not using any parameter pack.如果threadProc()
不使用任何参数包,一切都会正常工作。 Is there a correct way to launch a thread with variadic thread function?是否有正确的方法来启动带有可变参数线程 function 的线程?
your first argument is a function pointer, hence use您的第一个参数是 function 指针,因此使用
thread t{threadProc<void(*)(int)>, 1, callback};
Here https://godbolt.org/z/Hzp9EP这里https://godbolt.org/z/Hzp9EP
There is nothing wrong with your code.您的代码没有任何问题。 This seems to just be a bug in GCC, which has nothing to do with threads.这似乎只是GCC中的一个bug,与线程无关。 A minimal test case that reproduces the bug is:重现该错误的最小测试用例是:
template <typename... T>
void foo(T...) {}
int main()
{
auto* pfoo = foo<void(int)>;
return 0;
}
It seems that GCC does not like the fact that foo
has a parameter of type void(int)
.似乎 GCC 不喜欢foo
具有void(int)
类型的参数这一事实。 Yet the rules of the language are clear: this is allowed, and the function type is adjusted to the corresponding function pointer type when it appears as a parameter type.然而语言的规则很明确:这是允许的,并且当 function 类型作为参数类型出现时,它会调整为对应的 function 指针类型。
Other compilers seem to have no issue with it.其他编译器似乎没有问题。 See https://godbolt.org/z/tgaV7B见https://godbolt.org/z/tgaV7B
As a workaround, you can write:作为一种解决方法,您可以编写:
thread t(threadProc<void(*)(int)>, 1, callback);
Or:或者:
thread t(threadProc<decltype(&callback)>, 1, callback);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.