aboutsummaryrefslogtreecommitdiffstats
path: root/include/dumb_timer_queue.h
diff options
context:
space:
mode:
Diffstat (limited to 'include/dumb_timer_queue.h')
-rw-r--r--include/dumb_timer_queue.h31
1 files changed, 29 insertions, 2 deletions
diff --git a/include/dumb_timer_queue.h b/include/dumb_timer_queue.h
index 185725e..ebb8bb1 100644
--- a/include/dumb_timer_queue.h
+++ b/include/dumb_timer_queue.h
@@ -21,15 +21,36 @@ namespace crow
return q;
}
- void add(std::function<void()> f)
+ using key = std::pair<dumb_timer_queue*, int>;
+
+ void cancel(key& k)
+ {
+ auto self = k.first;
+ k.first = nullptr;
+ if (!self)
+ return;
+ self->mutex_.lock();
+ unsigned int index = (unsigned int)(k.second - self->step_);
+ if (index < self->dq_.size())
+ self->dq_[index].second = nullptr;
+ self->mutex_.unlock();
+ }
+
+ key add(std::function<void()> f)
{
+ mutex_.lock();
dq_.emplace_back(std::chrono::steady_clock::now(), std::move(f));
+ int ret = step_+dq_.size()-1;
+ mutex_.unlock();
+ CROW_LOG_DEBUG << "timer add inside: " << this << ' ' << ret ;
+ return {this, ret};
}
void process()
{
if (!io_service_)
return;
+ mutex_.lock();
auto now = std::chrono::steady_clock::now();
while(!dq_.empty())
{
@@ -38,10 +59,14 @@ namespace crow
break;
if (x.second)
{
- io_service_->post(std::move(x.second));
+ CROW_LOG_DEBUG << "timer call: " << this << ' ' << step_;
+ //io_service_->post(std::move(x.second));
+ x.second();
}
dq_.pop_front();
+ step_++;
}
+ mutex_.unlock();
}
void set_io_service(boost::asio::io_service& io_service)
@@ -57,6 +82,8 @@ namespace crow
int tick{5};
boost::asio::io_service* io_service_{};
std::deque<std::pair<decltype(std::chrono::steady_clock::now()), std::function<void()>>> dq_;
+ std::mutex mutex_;
+ int step_{};
};
}
}