【发布时间】:2015-06-21 16:08:40
【问题描述】:
我有一些代码使用std::thread 周围的包装类,它使用计时器结构(基于boost::asio)每5000 毫秒调用一次methodToCallEachIteration():
class OurThreadWrapperClass{
OurThreadWrapperClass(boost::asio::io_service& = generic_timer_queue_s());
};
class A {
A() : thread1(_TimerIOService){
thread1.setInterval(5000);
// This sets the callback function, to be called every INTERVAL ms.
thread1.start([this](OurThreadWrapperClass&) {
this->methodToCallEachIteration();
});
}
void callAFunctionHere(std::bitset<10> arg) {
// ...
}
void methodToCallEachIteration() {
// ...
}
struct TimerService {
constexpr static const size_t num_threads{2};
TimerService(){
for(auto& t: _threads){
t = std::thread([this](){
boost::asio::io_service::work keepalive{_ioservice};
callAFunctionHere(_anArgument); // The method and arg not recognised
(void)keepalive;
_ioservice.run();
});
}
}
operator boost::asio::io_service&() {
return _ioservice;
}
boost::asio::io_service _ioservice{num_threads};
std::thread _threads[num_threads];
};
OurThreadWrapperClass thread1;
TimerService _TimerIOService;
std::bitset<10> _anArgument;
};
我遇到的问题是我想从准备线程的 TimerService 中调用callAFunctionHere()。我无法在 TimerService 中移动此功能。但是,编译器抱怨它找不到callAFunctionHere() 或_anArgument:
error: cannot call member function callAFunctionHere(std::bitset<10>) without object
error: 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = TimerService::TimerService()::__lambda19; _Args = {}]', declared using local type TimerService::TimerService()::__lambda19', is used but never defined [-fpermissive]
thread(_Callable&& __f, _Args&&... __args)
我认为我需要更改 A::A() 中的 lambda,以便编译器可以“看到”方法和参数,但我不太确定如何?
【问题讨论】:
-
你可能想在这里重新考虑你的封装。
A和TimerService的功能似乎很混乱,如果意图是让TimerService中的功能可在其他类中重复使用,那么将其设置为A的嵌套类似乎是多余的。 -
BTW
thread1在_TimerIOService之前构造,因此您将未初始化的对象传递给thread1的构造函数。
标签: c++ multithreading c++11 lambda boost-asio