| 1 | // |
|---|---|
| 2 | // Copyright (c) 2022 Klemens Morgenstern (klemens.morgenstern@gmx.net) |
| 3 | // |
| 4 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 5 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 6 | // |
| 7 | |
| 8 | #include <boost/cobalt/thread.hpp> |
| 9 | #include <boost/asio/steady_timer.hpp> |
| 10 | |
| 11 | #include <boost/test/unit_test.hpp> |
| 12 | #include "test.hpp" |
| 13 | #include "boost/cobalt/spawn.hpp" |
| 14 | |
| 15 | boost::cobalt::thread thr() |
| 16 | { |
| 17 | boost::asio::steady_timer tim{co_await boost::asio::this_coro::executor, std::chrono::milliseconds(100)}; |
| 18 | |
| 19 | auto exec = co_await boost::asio::this_coro::executor; |
| 20 | co_await tim.async_wait(token: boost::cobalt::use_op); |
| 21 | } |
| 22 | |
| 23 | BOOST_AUTO_TEST_SUITE(thread); |
| 24 | |
| 25 | BOOST_AUTO_TEST_CASE(run) |
| 26 | { |
| 27 | auto t = thr(); |
| 28 | |
| 29 | t.join(); |
| 30 | BOOST_CHECK_THROW(t.get_executor(), boost::asio::execution::bad_executor); |
| 31 | } |
| 32 | |
| 33 | |
| 34 | boost::cobalt::thread thr_stop() |
| 35 | { |
| 36 | boost::asio::steady_timer tim{co_await boost::asio::this_coro::executor, std::chrono::milliseconds(100)}; |
| 37 | |
| 38 | #if !defined(BOOST_COBALT_USE_IO_CONTEXT) |
| 39 | auto exec = co_await boost::asio::this_coro::executor; |
| 40 | auto execp = exec.target<boost::asio::io_context::executor_type>(); |
| 41 | BOOST_ASSERT(execp != nullptr); |
| 42 | auto exc = *execp; |
| 43 | #else |
| 44 | auto exc = co_await boost::asio::this_coro::executor; |
| 45 | #endif |
| 46 | |
| 47 | exc.context().stop(); |
| 48 | co_await tim.async_wait(token: boost::cobalt::use_op); |
| 49 | } |
| 50 | |
| 51 | BOOST_AUTO_TEST_CASE(stop) |
| 52 | { |
| 53 | auto t = thr_stop(); |
| 54 | t.join(); |
| 55 | } |
| 56 | |
| 57 | CO_TEST_CASE(await_thread) |
| 58 | { |
| 59 | co_await thr(); |
| 60 | |
| 61 | auto th = thr_stop(); |
| 62 | boost::asio::steady_timer tim{co_await boost::asio::this_coro::executor, std::chrono::milliseconds(200)}; |
| 63 | co_await tim.async_wait(token: boost::cobalt::use_op); |
| 64 | co_await th; |
| 65 | try { |
| 66 | BOOST_CHECK_THROW(co_await th, boost::system::system_error); |
| 67 | } catch(...) {} |
| 68 | } |
| 69 | |
| 70 | boost::cobalt::task<std::thread::id> on_thread() |
| 71 | { |
| 72 | co_return std::this_thread::get_id(); |
| 73 | } |
| 74 | |
| 75 | CO_TEST_CASE(spawn_onto_thread) |
| 76 | { |
| 77 | using namespace boost; |
| 78 | auto t = thr(); |
| 79 | |
| 80 | auto id = co_await cobalt::spawn(executor: t.get_executor(), t: on_thread(), token: cobalt::use_op); |
| 81 | auto id2 = t.get_id(); |
| 82 | auto id3 = std::this_thread::get_id(); |
| 83 | |
| 84 | BOOST_CHECK(id == id2); |
| 85 | BOOST_CHECK(id3 != id); |
| 86 | |
| 87 | if (t.joinable()) |
| 88 | t.join(); |
| 89 | } |
| 90 | |
| 91 | |
| 92 | BOOST_AUTO_TEST_SUITE_END(); |
