Your code /looks/ okay-ish.
I'm not sure how you are reaching the conclusion that your completion handler doesn't "[...] fire (with an error code) when I reset the pointer". You are ignoring this case (there is no else
branch in the lambda).
How about writing the logic more clearly?
void foo(int clientId) {
shared_timer& timer = timersByClientId[clientId];
if (!timer)
onLogonChangeCallback(clientId, true);
timer = make_timer(); // reset
timer->async_wait([this, clientId](const boost::system::error_code& err) {
if (!err)
onLogonChangeCallback(clientId, false);
});
}
Here's a full demo with that else
branch to let you see what is going on. I assumed 1 service thread.
See it Live On Coliru.
The test load is 100 session activities on 16 accounts in ~0.5s. The total running time is ~1.5s because I have reduced the session expiration from 6s to 1s for Coliru.
If you didn't want the destructor of LogonManager to wait for all sessions to expire, then clear the session table before joining the background thread:
~LogonMonitor() {
work = boost::none;
timersByClientId.clear();
background.join();
}
Full Listing
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/optional.hpp>
#include <boost/make_shared.hpp>
struct LogonMonitor {
LogonMonitor()
: work(io_service::work(replyService)), background([this]{ replyService.run(); })
{ }
~LogonMonitor() {
work = boost::none;
// timersByClientId.clear();
background.join();
}
void foo(int clientId) {
shared_timer& timer = timersByClientId[clientId];
if (!timer)
onLogonChangeCallback(clientId, true);
timer = make_timer(); // reset
timer->async_wait([this, clientId](const boost::system::error_code& err) {
if (!err)
onLogonChangeCallback(clientId, false);
else
std::cout << "(cancel " << clientId << " timer)" << std::endl;
});
}
private:
using io_service = boost::asio::io_service;
using timer = boost::asio::deadline_timer;
using shared_timer = boost::shared_ptr<timer>;
io_service replyService;
boost::optional<io_service::work> work;
boost::thread background;
std::map<int, shared_timer> timersByClientId;
shared_timer make_timer() {
return boost::make_shared<timer>(replyService, boost::posix_time::seconds(/*6*/1));
}
void onLogonChangeCallback(int clientId, bool newLogon)
{
std::cout << __FUNCTION__ << "(" << clientId << ", " << newLogon << ")" << std::endl;
}
};
int main()
{
LogonMonitor instance;
for (int i = 0; i < 100; ++i)
{
instance.foo(rand() % 16);
boost::this_thread::sleep_for(boost::chrono::milliseconds(rand() % 10));
}
}