work_stealing.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright Oliver Kowalke 2015.
  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. //
  6. #ifndef BOOST_FIBERS_ALGO_WORK_STEALING_H
  7. #define BOOST_FIBERS_ALGO_WORK_STEALING_H
  8. #include <atomic>
  9. #include <condition_variable>
  10. #include <chrono>
  11. #include <cstddef>
  12. #include <cstdint>
  13. #include <mutex>
  14. #include <vector>
  15. #include <boost/config.hpp>
  16. #include <boost/intrusive_ptr.hpp>
  17. #include <boost/fiber/algo/algorithm.hpp>
  18. #include <boost/fiber/context.hpp>
  19. #include <boost/fiber/detail/config.hpp>
  20. #include <boost/fiber/detail/context_spinlock_queue.hpp>
  21. #include <boost/fiber/detail/context_spmc_queue.hpp>
  22. #include <boost/fiber/scheduler.hpp>
  23. #ifdef BOOST_HAS_ABI_HEADERS
  24. # include BOOST_ABI_PREFIX
  25. #endif
  26. namespace boost {
  27. namespace fibers {
  28. namespace algo {
  29. class BOOST_FIBERS_DECL work_stealing : public algorithm {
  30. private:
  31. static std::atomic< std::uint32_t > counter_;
  32. static std::vector< intrusive_ptr< work_stealing > > schedulers_;
  33. std::uint32_t id_;
  34. std::uint32_t thread_count_;
  35. #ifdef BOOST_FIBERS_USE_SPMC_QUEUE
  36. detail::context_spmc_queue rqueue_{};
  37. #else
  38. detail::context_spinlock_queue rqueue_{};
  39. #endif
  40. std::mutex mtx_{};
  41. std::condition_variable cnd_{};
  42. bool flag_{ false };
  43. bool suspend_;
  44. static void init_( std::uint32_t, std::vector< intrusive_ptr< work_stealing > > &);
  45. public:
  46. work_stealing( std::uint32_t, bool = false);
  47. work_stealing( work_stealing const&) = delete;
  48. work_stealing( work_stealing &&) = delete;
  49. work_stealing & operator=( work_stealing const&) = delete;
  50. work_stealing & operator=( work_stealing &&) = delete;
  51. void awakened( context *) noexcept override;
  52. context * pick_next() noexcept override;
  53. virtual context * steal() noexcept {
  54. return rqueue_.steal();
  55. }
  56. bool has_ready_fibers() const noexcept override {
  57. return ! rqueue_.empty();
  58. }
  59. void suspend_until( std::chrono::steady_clock::time_point const&) noexcept override;
  60. void notify() noexcept override;
  61. };
  62. }}}
  63. #ifdef BOOST_HAS_ABI_HEADERS
  64. # include BOOST_ABI_SUFFIX
  65. #endif
  66. #endif // BOOST_FIBERS_ALGO_WORK_STEALING_H