Skip to content

Commit

Permalink
Do not wait for cancellation signal (#4664)
Browse files Browse the repository at this point in the history
* Do not wait for cancelation signal

* Test

* Explicit constructor
  • Loading branch information
pwojcikdev authored Jul 2, 2024
1 parent f7232cd commit 6a802b2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
22 changes: 21 additions & 1 deletion nano/core_test/async.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,30 @@ TEST (async, cancellation)

cancellation.emit ();

ASSERT_EQ (fut.wait_for (500ms), std::future_status::ready);
ASSERT_EQ (fut.wait_for (1s), std::future_status::ready);
ASSERT_NO_THROW (fut.get ());
}

// Test that cancellation signal behaves well when the cancellation is emitted after the task has completed
TEST (async, cancellation_lifetime)
{
test_context ctx;

nano::async::cancellation cancellation{ ctx.strand };
{
auto fut = asio::co_spawn (
ctx.strand,
[&] () -> asio::awaitable<void> {
co_await nano::async::sleep_for (100ms);
},
asio::bind_cancellation_slot (cancellation.slot (), asio::use_future));
ASSERT_EQ (fut.wait_for (1s), std::future_status::ready);
fut.get ();
}
auto cancel_fut = cancellation.emit ();
ASSERT_EQ (cancel_fut.wait_for (1s), std::future_status::ready);
}

TEST (async, task)
{
nano::test::system system;
Expand Down
18 changes: 8 additions & 10 deletions nano/lib/async.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class cancellation
public:
explicit cancellation (nano::async::strand & strand) :
strand{ strand },
signal{ std::make_unique<asio::cancellation_signal> () }
signal{ std::make_shared<asio::cancellation_signal> () }
{
}

Expand All @@ -49,12 +49,11 @@ class cancellation
};

public:
void emit (asio::cancellation_type type = asio::cancellation_type::all)
auto emit (asio::cancellation_type type = asio::cancellation_type::all)
{
asio::dispatch (strand, asio::use_future ([this, type] () {
signal->emit (type);
}))
.wait ();
return asio::dispatch (strand, asio::use_future ([signal_l = signal, type] () {
signal_l->emit (type);
}));
}

auto slot ()
Expand All @@ -67,9 +66,8 @@ class cancellation
nano::async::strand & strand;

private:
std::unique_ptr<asio::cancellation_signal> signal; // Wrap the signal in a unique_ptr to enable moving

bool slotted{ false };
std::shared_ptr<asio::cancellation_signal> signal;
bool slotted{ false }; // For debugging purposes
};

/**
Expand All @@ -82,7 +80,7 @@ class task
// Only thread-like void tasks are supported for now
using value_type = void;

task (nano::async::strand & strand) :
explicit task (nano::async::strand & strand) :
strand{ strand },
cancellation{ strand }
{
Expand Down

0 comments on commit 6a802b2

Please sign in to comment.