context.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. // Copyright Oliver Kowalke 2013.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_FIBERS_CONTEXT_H
  6. #define BOOST_FIBERS_CONTEXT_H
  7. #include <atomic>
  8. #include <chrono>
  9. #include <cstdint>
  10. #include <exception>
  11. #include <functional>
  12. #include <iostream>
  13. #include <map>
  14. #include <memory>
  15. #include <tuple>
  16. #include <type_traits>
  17. #include <utility>
  18. #include <boost/assert.hpp>
  19. #include <boost/config.hpp>
  20. #include <boost/core/ignore_unused.hpp>
  21. #if defined(BOOST_NO_CXX17_STD_APPLY)
  22. #include <boost/context/detail/apply.hpp>
  23. #endif
  24. #include <boost/context/fiber.hpp>
  25. #include <boost/context/stack_context.hpp>
  26. #include <boost/intrusive/list.hpp>
  27. #include <boost/intrusive/parent_from_member.hpp>
  28. #include <boost/intrusive_ptr.hpp>
  29. #include <boost/intrusive/set.hpp>
  30. #include <boost/intrusive/slist.hpp>
  31. #include <boost/fiber/detail/config.hpp>
  32. #include <boost/fiber/detail/data.hpp>
  33. #include <boost/fiber/detail/decay_copy.hpp>
  34. #include <boost/fiber/detail/fss.hpp>
  35. #include <boost/fiber/detail/spinlock.hpp>
  36. #include <boost/fiber/exceptions.hpp>
  37. #include <boost/fiber/fixedsize_stack.hpp>
  38. #include <boost/fiber/policy.hpp>
  39. #include <boost/fiber/properties.hpp>
  40. #include <boost/fiber/segmented_stack.hpp>
  41. #include <boost/fiber/type.hpp>
  42. #ifdef BOOST_HAS_ABI_HEADERS
  43. # include BOOST_ABI_PREFIX
  44. #endif
  45. #ifdef _MSC_VER
  46. # pragma warning(push)
  47. # pragma warning(disable:4251)
  48. #endif
  49. namespace boost {
  50. namespace fibers {
  51. class context;
  52. class fiber;
  53. class scheduler;
  54. namespace detail {
  55. struct wait_tag;
  56. typedef intrusive::list_member_hook<
  57. intrusive::tag< wait_tag >,
  58. intrusive::link_mode<
  59. intrusive::auto_unlink
  60. >
  61. > wait_hook;
  62. // declaration of the functor that converts between
  63. // the context class and the wait-hook
  64. struct wait_functor {
  65. // required types
  66. using hook_type = wait_hook;
  67. using hook_ptr = hook_type *;
  68. using const_hook_ptr = const hook_type *;
  69. using value_type = context;
  70. using pointer = value_type *;
  71. using const_pointer = const value_type *;
  72. // required static functions
  73. static hook_ptr to_hook_ptr( value_type &value);
  74. static const_hook_ptr to_hook_ptr( value_type const& value);
  75. static pointer to_value_ptr( hook_ptr n);
  76. static const_pointer to_value_ptr( const_hook_ptr n);
  77. };
  78. struct ready_tag;
  79. typedef intrusive::list_member_hook<
  80. intrusive::tag< ready_tag >,
  81. intrusive::link_mode<
  82. intrusive::auto_unlink
  83. >
  84. > ready_hook;
  85. struct sleep_tag;
  86. typedef intrusive::set_member_hook<
  87. intrusive::tag< sleep_tag >,
  88. intrusive::link_mode<
  89. intrusive::auto_unlink
  90. >
  91. > sleep_hook;
  92. struct worker_tag;
  93. typedef intrusive::list_member_hook<
  94. intrusive::tag< worker_tag >,
  95. intrusive::link_mode<
  96. intrusive::auto_unlink
  97. >
  98. > worker_hook;
  99. struct terminated_tag;
  100. typedef intrusive::slist_member_hook<
  101. intrusive::tag< terminated_tag >,
  102. intrusive::link_mode<
  103. intrusive::safe_link
  104. >
  105. > terminated_hook;
  106. struct remote_ready_tag;
  107. typedef intrusive::slist_member_hook<
  108. intrusive::tag< remote_ready_tag >,
  109. intrusive::link_mode<
  110. intrusive::safe_link
  111. >
  112. > remote_ready_hook;
  113. }
  114. class BOOST_FIBERS_DECL context {
  115. public:
  116. typedef intrusive::list<
  117. context,
  118. intrusive::function_hook< detail::wait_functor >,
  119. intrusive::constant_time_size< false >
  120. > wait_queue_t;
  121. private:
  122. friend class dispatcher_context;
  123. friend class main_context;
  124. template< typename Fn, typename ... Arg > friend class worker_context;
  125. friend class scheduler;
  126. struct fss_data {
  127. void * vp{ nullptr };
  128. detail::fss_cleanup_function::ptr_t cleanup_function{};
  129. fss_data() noexcept = default;
  130. fss_data( void * vp_,
  131. detail::fss_cleanup_function::ptr_t fn) noexcept :
  132. vp( vp_),
  133. cleanup_function(std::move( fn)) {
  134. BOOST_ASSERT( cleanup_function);
  135. }
  136. void do_cleanup() {
  137. ( * cleanup_function)( vp);
  138. }
  139. };
  140. typedef std::map< uintptr_t, fss_data > fss_data_t;
  141. #if ! defined(BOOST_FIBERS_NO_ATOMICS)
  142. std::atomic< std::size_t > use_count_;
  143. #else
  144. std::size_t use_count_;
  145. #endif
  146. #if ! defined(BOOST_FIBERS_NO_ATOMICS)
  147. detail::remote_ready_hook remote_ready_hook_{};
  148. #endif
  149. detail::spinlock splk_{};
  150. bool terminated_{ false };
  151. wait_queue_t wait_queue_{};
  152. public:
  153. detail::wait_hook wait_hook_{};
  154. #if ! defined(BOOST_FIBERS_NO_ATOMICS)
  155. std::atomic< std::intptr_t > twstatus{ 0 };
  156. #endif
  157. private:
  158. scheduler * scheduler_{ nullptr };
  159. fss_data_t fss_data_{};
  160. detail::sleep_hook sleep_hook_{};
  161. detail::ready_hook ready_hook_{};
  162. detail::terminated_hook terminated_hook_{};
  163. detail::worker_hook worker_hook_{};
  164. fiber_properties * properties_{ nullptr };
  165. boost::context::fiber c_{};
  166. std::chrono::steady_clock::time_point tp_;
  167. type type_;
  168. launch policy_;
  169. context( std::size_t initial_count, type t, launch policy) noexcept :
  170. use_count_{ initial_count },
  171. tp_{ (std::chrono::steady_clock::time_point::max)() },
  172. type_{ t },
  173. policy_{ policy } {
  174. }
  175. public:
  176. class id {
  177. private:
  178. context * impl_{ nullptr };
  179. public:
  180. id() = default;
  181. explicit id( context * impl) noexcept :
  182. impl_{ impl } {
  183. }
  184. bool operator==( id const& other) const noexcept {
  185. return impl_ == other.impl_;
  186. }
  187. bool operator!=( id const& other) const noexcept {
  188. return impl_ != other.impl_;
  189. }
  190. bool operator<( id const& other) const noexcept {
  191. return impl_ < other.impl_;
  192. }
  193. bool operator>( id const& other) const noexcept {
  194. return other.impl_ < impl_;
  195. }
  196. bool operator<=( id const& other) const noexcept {
  197. return ! ( * this > other);
  198. }
  199. bool operator>=( id const& other) const noexcept {
  200. return ! ( * this < other);
  201. }
  202. template< typename charT, class traitsT >
  203. friend std::basic_ostream< charT, traitsT > &
  204. operator<<( std::basic_ostream< charT, traitsT > & os, id const& other) {
  205. if ( nullptr != other.impl_) {
  206. return os << other.impl_;
  207. }
  208. return os << "{not-valid}";
  209. }
  210. explicit operator bool() const noexcept {
  211. return nullptr != impl_;
  212. }
  213. bool operator!() const noexcept {
  214. return nullptr == impl_;
  215. }
  216. };
  217. static context * active() noexcept;
  218. static void reset_active() noexcept;
  219. context( context const&) = delete;
  220. context( context &&) = delete;
  221. context & operator=( context const&) = delete;
  222. context & operator=( context &&) = delete;
  223. friend bool
  224. operator==( context const& lhs, context const& rhs) noexcept {
  225. return & lhs == & rhs;
  226. }
  227. virtual ~context();
  228. scheduler * get_scheduler() const noexcept {
  229. return scheduler_;
  230. }
  231. id get_id() const noexcept;
  232. bool is_resumable() const noexcept {
  233. return static_cast<bool>(c_);
  234. }
  235. void resume() noexcept;
  236. void resume( detail::spinlock_lock &) noexcept;
  237. void resume( context *) noexcept;
  238. void suspend() noexcept;
  239. void suspend( detail::spinlock_lock &) noexcept;
  240. boost::context::fiber suspend_with_cc() noexcept;
  241. boost::context::fiber terminate() noexcept;
  242. void join();
  243. void yield() noexcept;
  244. bool wait_until( std::chrono::steady_clock::time_point const&) noexcept;
  245. bool wait_until( std::chrono::steady_clock::time_point const&,
  246. detail::spinlock_lock &) noexcept;
  247. void schedule( context *) noexcept;
  248. bool is_context( type t) const noexcept {
  249. return type::none != ( type_ & t);
  250. }
  251. void * get_fss_data( void const * vp) const;
  252. void set_fss_data(
  253. void const * vp,
  254. detail::fss_cleanup_function::ptr_t const& cleanup_fn,
  255. void * data,
  256. bool cleanup_existing);
  257. void set_properties( fiber_properties * props) noexcept;
  258. fiber_properties * get_properties() const noexcept {
  259. return properties_;
  260. }
  261. launch get_policy() const noexcept {
  262. return policy_;
  263. }
  264. bool worker_is_linked() const noexcept;
  265. bool ready_is_linked() const noexcept;
  266. bool remote_ready_is_linked() const noexcept;
  267. bool sleep_is_linked() const noexcept;
  268. bool terminated_is_linked() const noexcept;
  269. bool wait_is_linked() const noexcept;
  270. template< typename List >
  271. void worker_link( List & lst) noexcept {
  272. static_assert( std::is_same< typename List::value_traits::hook_type, detail::worker_hook >::value, "not a worker-queue");
  273. BOOST_ASSERT( ! worker_is_linked() );
  274. lst.push_back( * this);
  275. }
  276. template< typename List >
  277. void ready_link( List & lst) noexcept {
  278. static_assert( std::is_same< typename List::value_traits::hook_type, detail::ready_hook >::value, "not a ready-queue");
  279. BOOST_ASSERT( ! ready_is_linked() );
  280. lst.push_back( * this);
  281. }
  282. template< typename List >
  283. void remote_ready_link( List & lst) noexcept {
  284. static_assert( std::is_same< typename List::value_traits::hook_type, detail::remote_ready_hook >::value, "not a remote-ready-queue");
  285. BOOST_ASSERT( ! remote_ready_is_linked() );
  286. lst.push_back( * this);
  287. }
  288. template< typename Set >
  289. void sleep_link( Set & set) noexcept {
  290. static_assert( std::is_same< typename Set::value_traits::hook_type,detail::sleep_hook >::value, "not a sleep-queue");
  291. BOOST_ASSERT( ! sleep_is_linked() );
  292. set.insert( * this);
  293. }
  294. template< typename List >
  295. void terminated_link( List & lst) noexcept {
  296. static_assert( std::is_same< typename List::value_traits::hook_type, detail::terminated_hook >::value, "not a terminated-queue");
  297. BOOST_ASSERT( ! terminated_is_linked() );
  298. lst.push_back( * this);
  299. }
  300. template< typename List >
  301. void wait_link( List & lst) noexcept {
  302. static_assert( std::is_same< typename List::value_traits::hook_type, detail::wait_hook >::value, "not a wait-queue");
  303. BOOST_ASSERT( ! wait_is_linked() );
  304. lst.push_back( * this);
  305. }
  306. void worker_unlink() noexcept;
  307. void ready_unlink() noexcept;
  308. void sleep_unlink() noexcept;
  309. void wait_unlink() noexcept;
  310. void detach() noexcept;
  311. void attach( context *) noexcept;
  312. friend void intrusive_ptr_add_ref( context * ctx) noexcept {
  313. BOOST_ASSERT( nullptr != ctx);
  314. ctx->use_count_.fetch_add( 1, std::memory_order_relaxed);
  315. }
  316. friend void intrusive_ptr_release( context * ctx) noexcept {
  317. BOOST_ASSERT( nullptr != ctx);
  318. if ( 1 == ctx->use_count_.fetch_sub( 1, std::memory_order_release) ) {
  319. std::atomic_thread_fence( std::memory_order_acquire);
  320. boost::context::fiber c = std::move( ctx->c_);
  321. // destruct context
  322. ctx->~context();
  323. // deallocated stack
  324. std::move( c).resume();
  325. }
  326. }
  327. };
  328. inline
  329. bool operator<( context const& l, context const& r) noexcept {
  330. return l.get_id() < r.get_id();
  331. }
  332. template< typename Fn, typename ... Arg >
  333. class worker_context final : public context {
  334. private:
  335. typename std::decay< Fn >::type fn_;
  336. std::tuple< Arg ... > arg_;
  337. boost::context::fiber
  338. run_( boost::context::fiber && c) {
  339. {
  340. // fn and tpl must be destroyed before calling terminate()
  341. auto fn = std::move( fn_);
  342. auto arg = std::move( arg_);
  343. #if (defined(BOOST_USE_UCONTEXT)||defined(BOOST_USE_WINFIB))
  344. std::move( c).resume();
  345. #else
  346. boost::ignore_unused(c);
  347. #endif
  348. #if defined(BOOST_NO_CXX17_STD_APPLY)
  349. boost::context::detail::apply( std::move( fn), std::move( arg) );
  350. #else
  351. std::apply( std::move( fn), std::move( arg) );
  352. #endif
  353. }
  354. // terminate context
  355. return terminate();
  356. }
  357. public:
  358. template< typename StackAlloc >
  359. worker_context( launch policy,
  360. boost::context::preallocated const& palloc, StackAlloc && salloc,
  361. Fn && fn, Arg ... arg) :
  362. context{ 1, type::worker_context, policy },
  363. fn_( std::forward< Fn >( fn) ),
  364. arg_( std::forward< Arg >( arg) ... ) {
  365. c_ = boost::context::fiber{ std::allocator_arg, palloc, std::forward< StackAlloc >( salloc),
  366. std::bind( & worker_context::run_, this, std::placeholders::_1) };
  367. #if (defined(BOOST_USE_UCONTEXT)||defined(BOOST_USE_WINFIB))
  368. c_ = std::move( c_).resume();
  369. #endif
  370. }
  371. };
  372. template< typename StackAlloc, typename Fn, typename ... Arg >
  373. static intrusive_ptr< context > make_worker_context( launch policy,
  374. StackAlloc && salloc,
  375. Fn && fn, Arg ... arg) {
  376. typedef worker_context< Fn, Arg ... > context_t;
  377. auto sctx = salloc.allocate();
  378. // reserve space for control structure
  379. void * storage = reinterpret_cast< void * >(
  380. ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( context_t) ) )
  381. & ~ static_cast< uintptr_t >( 0xff) );
  382. void * stack_bottom = reinterpret_cast< void * >(
  383. reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sctx.size) );
  384. const std::size_t size = reinterpret_cast< uintptr_t >( storage) - reinterpret_cast< uintptr_t >( stack_bottom);
  385. // placement new of context on top of fiber's stack
  386. return intrusive_ptr< context >{
  387. new ( storage) context_t{
  388. policy,
  389. boost::context::preallocated{ storage, size, sctx },
  390. std::forward< StackAlloc >( salloc),
  391. std::forward< Fn >( fn),
  392. std::forward< Arg >( arg) ... } };
  393. }
  394. namespace detail {
  395. inline
  396. wait_functor::hook_ptr wait_functor::to_hook_ptr( wait_functor::value_type & value) {
  397. return & value.wait_hook_;
  398. }
  399. inline
  400. wait_functor::const_hook_ptr wait_functor::to_hook_ptr( wait_functor::value_type const& value) {
  401. return & value.wait_hook_;
  402. }
  403. inline
  404. wait_functor::pointer wait_functor::to_value_ptr( wait_functor::hook_ptr n) {
  405. return intrusive::get_parent_from_member< context >( n, & context::wait_hook_);
  406. }
  407. inline
  408. wait_functor::const_pointer wait_functor::to_value_ptr( wait_functor::const_hook_ptr n) {
  409. return intrusive::get_parent_from_member< context >( n, & context::wait_hook_);
  410. }
  411. }}}
  412. #ifdef _MSC_VER
  413. # pragma warning(pop)
  414. #endif
  415. #ifdef BOOST_HAS_ABI_HEADERS
  416. # include BOOST_ABI_SUFFIX
  417. #endif
  418. #endif // BOOST_FIBERS_CONTEXT_H