I have some code using a wrapper class around std::thread
, which is using a timer struct (based upon boost::asio
), to call methodToCallEachIteration()
every 5000 milliseconds:
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;
};
The problem I am having is that I would like to call callAFunctionHere()
, from within the TimerService which prepares the threads. I cannot move this function inside TimerService. However, the compiler is complaining that it cannot find callAFunctionHere()
or _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)
I think I need to alter the lambda in A::A()
so that the compiler can "see" the method and argument but I am not too sure how?
In the lambda that is calling
callAFunctionHere
, thethis
that is captured is the one for the instance ofclass A::TimerService
, but you are trying to implicitly use members of anclass A
instance. You need a reference to an object of typeA
, and use that object's members.Notice that
_TimerIOService
needs to come beforethread1
. And now, the lambda inA::TimerService
usesa_
to access the desired members.