Do not wait for cancellation signal (#4664)

* Do not wait for cancelation signal

* Test

* Explicit constructor
This commit is contained in:
Piotr Wójcik 2024-07-02 09:48:12 +02:00 committed by GitHub
commit 6a802b2359
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 29 additions and 11 deletions

View file

@ -56,10 +56,30 @@ TEST (async, cancellation)
cancellation.emit (); 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 ()); 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) TEST (async, task)
{ {
nano::test::system system; nano::test::system system;

View file

@ -30,7 +30,7 @@ class cancellation
public: public:
explicit cancellation (nano::async::strand & strand) : explicit cancellation (nano::async::strand & strand) :
strand{ strand }, strand{ strand },
signal{ std::make_unique<asio::cancellation_signal> () } signal{ std::make_shared<asio::cancellation_signal> () }
{ {
} }
@ -49,12 +49,11 @@ public:
}; };
public: 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] () { return asio::dispatch (strand, asio::use_future ([signal_l = signal, type] () {
signal->emit (type); signal_l->emit (type);
})) }));
.wait ();
} }
auto slot () auto slot ()
@ -67,9 +66,8 @@ public:
nano::async::strand & strand; nano::async::strand & strand;
private: private:
std::unique_ptr<asio::cancellation_signal> signal; // Wrap the signal in a unique_ptr to enable moving std::shared_ptr<asio::cancellation_signal> signal;
bool slotted{ false }; // For debugging purposes
bool slotted{ false };
}; };
/** /**
@ -82,7 +80,7 @@ public:
// Only thread-like void tasks are supported for now // Only thread-like void tasks are supported for now
using value_type = void; using value_type = void;
task (nano::async::strand & strand) : explicit task (nano::async::strand & strand) :
strand{ strand }, strand{ strand },
cancellation{ strand } cancellation{ strand }
{ {