Browse Source

workaround in old scheduler due to possible lifetime issues (#135)

pull/139/head
art-gor 4 years ago
committed by GitHub
parent
commit
c9fb624371
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      include/libp2p/protocol/common/asio/asio_scheduler.hpp
  2. 11
      src/protocol/common/asio/asio_scheduler.cpp
  3. 2
      test/libp2p/protocol/common/asio/asio_scheduler_test.cpp

5
include/libp2p/protocol/common/asio/asio_scheduler.hpp

@ -14,7 +14,8 @@ namespace libp2p::protocol {
class AsioScheduler : public Scheduler {
public:
AsioScheduler(boost::asio::io_context &io, SchedulerConfig config);
AsioScheduler(const std::shared_ptr<boost::asio::io_context> &io,
SchedulerConfig config);
~AsioScheduler() override;
@ -27,7 +28,7 @@ namespace libp2p::protocol {
void onImmediate();
boost::asio::io_context &io_;
std::weak_ptr<boost::asio::io_context> io_;
Ticks interval_;
boost::asio::deadline_timer timer_;
boost::posix_time::ptime started_;

11
src/protocol/common/asio/asio_scheduler.cpp

@ -9,11 +9,11 @@
namespace libp2p::protocol {
AsioScheduler::AsioScheduler(boost::asio::io_context &io,
AsioScheduler::AsioScheduler(const std::shared_ptr<boost::asio::io_context> &io,
SchedulerConfig config)
: io_(io),
interval_(config.period_msec),
timer_(io, boost::posix_time::milliseconds(interval_)),
timer_(*io, boost::posix_time::milliseconds(interval_)),
started_(boost::posix_time::microsec_clock::local_time()),
canceled_(std::make_shared<bool>(false)),
timer_cb_([this, canceled{canceled_}](
@ -28,7 +28,9 @@ namespace libp2p::protocol {
AsioScheduler::~AsioScheduler() {
*canceled_ = true;
if (!io_.expired()) {
timer_.cancel();
}
};
Scheduler::Ticks AsioScheduler::now() const {
@ -39,16 +41,19 @@ namespace libp2p::protocol {
void AsioScheduler::scheduleImmediate() {
if (!immediate_cb_scheduled_) {
immediate_cb_scheduled_ = true;
io_.post(immediate_cb_);
auto io = io_.lock();
if (io) io->post(immediate_cb_);
}
}
void AsioScheduler::onTimer() {
pulse(false);
if (!io_.expired()) {
timer_.expires_at(timer_.expires_at()
+ boost::posix_time::milliseconds(interval_));
timer_.async_wait(timer_cb_);
}
}
void AsioScheduler::onImmediate() {
if (immediate_cb_scheduled_) {

2
test/libp2p/protocol/common/asio/asio_scheduler_test.cpp

@ -21,7 +21,7 @@ TEST(AsioScheduler, Construct) {
auto context = injector.create<std::shared_ptr<boost::asio::io_context>>();
std::shared_ptr<Scheduler> scheduler =
std::make_shared<libp2p::protocol::AsioScheduler>(
*context, libp2p::protocol::SchedulerConfig{});
context, libp2p::protocol::SchedulerConfig{});
scheduler.reset();
context->run();
}

Loading…
Cancel
Save