context.hpp 16 KB

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