work_stealing.hpp 2.8 KB

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