Skip to content

Commit

Permalink
Implement io_service::process_events_until_complete
Browse files Browse the repository at this point in the history
  • Loading branch information
Uran198 committed Mar 8, 2018
1 parent 875b720 commit 94f03aa
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
27 changes: 27 additions & 0 deletions include/cppcoro/io_service.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ namespace cppcoro
const std::chrono::duration<REP, PERIOD>& delay,
cancellation_token cancellationToken = {}) noexcept;

/// Process events until the task completes.
///
/// \return
/// Result of the co_await task.
template<typename TASK>
decltype(auto) process_events_until_complete(TASK&& task);

/// Process events until the io_service is stopped.
///
/// \return
Expand Down Expand Up @@ -178,6 +185,26 @@ namespace cppcoro

};

template<typename TASK>
decltype(auto) io_service::process_events_until_complete(TASK&& task)
{
if (!task.is_ready())
{
auto callback = [](void* io) noexcept
{
static_cast<io_service*>(io)->stop();
};

auto starter = task.get_starter();
starter.start(cppcoro::detail::continuation{ callback, this });

process_events();
reset();
}

return std::forward<TASK>(task).operator co_await().await_resume();
}

class io_service::schedule_operation
{
public:
Expand Down
32 changes: 32 additions & 0 deletions test/io_service_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,36 @@ TEST_CASE_FIXTURE(io_service_fixture_with_threads<1>, "Many concurrent timers")
<< "ms");
}

TEST_CASE("io_service::process_events_until_complete(task<T>)")
{
cppcoro::io_service ioService;

auto makeTask = [](cppcoro::io_service& io) -> cppcoro::task<std::string>
{
co_await io.schedule();
co_return "foo";
};

auto task = makeTask(ioService);

CHECK(ioService.process_events_until_complete(task) == "foo");
CHECK(ioService.process_events_until_complete(makeTask(ioService)) == "foo");
}

TEST_CASE("io_service::process_events_until_complete(shared_task<T>)")
{
cppcoro::io_service ioService;

auto makeTask = [](cppcoro::io_service& io) -> cppcoro::shared_task<std::string>
{
co_await io.schedule();
co_return "foo";
};

auto task = makeTask(ioService);

CHECK(ioService.process_events_until_complete(task) == "foo");
CHECK(ioService.process_events_until_complete(makeTask(ioService)) == "foo");
}

TEST_SUITE_END();

0 comments on commit 94f03aa

Please sign in to comment.