【发布时间】:2018-01-15 17:56:11
【问题描述】:
我想控制threads,所以每个新发布的thread都会先通过我的代码。
这样,在下面的示例中,每个使用runThread() 发出的新线程都会首先调用下面的函数runInnerThread()(我在其中进行了某种初始化),然后调用所需的函数。
我试过这样写:
#include <iostream>
#include <thread>
template<typename _Callable, typename... _Args>
void runThreadInner(_Callable&& __f, _Args&&... __args) {
// My initializations...
__f(__args...);
// My finishing...
};
template<typename _Callable, typename... _Args>
bool runThread(_Callable&& __f, _Args&&... __args) {
std::thread t(std::bind(&runThreadInner,
std::forward<_Callable>(__f),
std::forward<_Args>(__args)...));
}
int main() {
runThread([]() {
std::cout << std::this_thread::get_id() << "Threading...\n";
});
return 0;
}
我从编译器收到一个错误,抱怨推断
runThreadInner()模板
main.cpp: In instantiation of ‘bool runThread(_Callable&&, _Args&& ...) [with _Callable = main()::__lambda0; _Args = {}]’:
main.cpp:43:3: required from here
main.cpp:27:38: error: no matching function for call to ‘bind(<unresolved overloaded function type>, main()::__lambda0)’
std::forward<_Args>(__args)...));
^
main.cpp:27:38: note: candidates are:
In file included from /usr/include/c++/4.8/memory:79:0,
from main.cpp:2:
/usr/include/c++/4.8/functional:1655:5: note: template<class _Func, class ... _BoundArgs> typename std::_Bind_helper<std::__or_<std::is_integral<typename std::decay<_Tp>::type>, std::is_enum<typename std::decay<_Tp>::type> >::value, _Func, _BoundArgs ...>::type std::bind(_Func&&, _BoundArgs&& ...)
bind(_Func&& __f, _BoundArgs&&... __args)
^
/usr/include/c++/4.8/functional:1655:5: note: template argument deduction/substitution failed:
main.cpp:27:38: note: couldn't deduce template parameter ‘_Func’
std::forward<_Args>(__args)...));
^
In file included from /usr/include/c++/4.8/memory:79:0,
from main.cpp:2:
/usr/include/c++/4.8/functional:1682:5: note: template<class _Result, class _Func, class ... _BoundArgs> typename std::_Bindres_helper<_Result, _Func, _BoundArgs>::type std::bind(_Func&&, _BoundArgs&& ...)
bind(_Func&& __f, _BoundArgs&&... __args)
^
/usr/include/c++/4.8/functional:1682:5: note: template argument deduction/substitution failed:
main.cpp:27:38: note: couldn't deduce template parameter ‘_Result’
std::forward<_Args>(__args)...));
我尝试显式定义模板,但没有成功:
template<typename _Callable, typename... _Args>
bool runThread(_Callable&& __f, _Args&&... __args) {
std::thread t(std::bind(&runThreadInner<_Callable, _Args>,
std::forward<_Callable>(__f),
std::forward<_Args>(__args)...));
}
有可能吗? 谢谢。
【问题讨论】:
-
为什么要拨打
bind?此外,您的 GCC 版本接近古老,并且没有完整的 C++11 支持。 -
另外,我确实希望您的
runThread对它启动的线程有某种簿记,以便您以后可以join它们。 -
这不是问题,但是以下划线开头后跟大写字母的名称(
_Callable等)和包含两个连续下划线的名称(__f等)保留供实现使用。不要在你的代码中使用它们。 -
代码问题:缺少#includes。简单的语法错误(多余的右括号)。以下划线和大写字母开头的标识符保留给系统使用。 stackoverflow.com/questions/228783/…
-
这个问题中的每一行代码,除了右括号和 main 的大部分内容,都有可能让我在代码审查中拒绝它的问题。这令人印象深刻。
标签: c++ multithreading c++11 stdthread