spinlock_ttas_adaptive.hpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // Copyright Oliver Kowalke 2016.
  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_SPINLOCK_TTAS_ADAPTIVE_H
  6. #define BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_H
  7. #include <atomic>
  8. #include <chrono>
  9. #include <cmath>
  10. #include <random>
  11. #include <thread>
  12. #include <boost/fiber/detail/config.hpp>
  13. #include <boost/fiber/detail/cpu_relax.hpp>
  14. #include <boost/fiber/detail/spinlock_status.hpp>
  15. // based on informations from:
  16. // https://software.intel.com/en-us/articles/benefitting-power-and-performance-sleep-loops
  17. // https://software.intel.com/en-us/articles/long-duration-spin-wait-loops-on-hyper-threading-technology-enabled-intel-processors
  18. namespace boost {
  19. namespace fibers {
  20. namespace detail {
  21. class spinlock_ttas_adaptive {
  22. private:
  23. template< typename FBSplk >
  24. friend class spinlock_rtm;
  25. std::atomic< spinlock_status > state_{ spinlock_status::unlocked };
  26. std::atomic< std::size_t > retries_{ 0 };
  27. public:
  28. spinlock_ttas_adaptive() = default;
  29. spinlock_ttas_adaptive( spinlock_ttas_adaptive const&) = delete;
  30. spinlock_ttas_adaptive & operator=( spinlock_ttas_adaptive const&) = delete;
  31. void lock() noexcept {
  32. static thread_local std::minstd_rand generator{ std::random_device{}() };
  33. std::size_t collisions = 0 ;
  34. for (;;) {
  35. std::size_t retries = 0;
  36. const std::size_t prev_retries = retries_.load( std::memory_order_relaxed);
  37. const std::size_t max_relax_retries = (std::min)(
  38. static_cast< std::size_t >( BOOST_FIBERS_SPIN_BEFORE_SLEEP0), 2 * prev_retries + 10);
  39. const std::size_t max_sleep_retries = (std::min)(
  40. static_cast< std::size_t >( BOOST_FIBERS_SPIN_BEFORE_YIELD), 2 * prev_retries + 10);
  41. // avoid using multiple pause instructions for a delay of a specific cycle count
  42. // the delay of cpu_relax() (pause on Intel) depends on the processor family
  43. // the cycle count can not guaranteed from one system to the next
  44. // -> check the shared variable 'state_' in between each cpu_relax() to prevent
  45. // unnecessarily long delays on some systems
  46. // test shared variable 'status_'
  47. // first access to 'state_' -> chache miss
  48. // sucessive acccess to 'state_' -> cache hit
  49. // if 'state_' was released by other fiber
  50. // cached 'state_' is invalidated -> cache miss
  51. while ( spinlock_status::locked == state_.load( std::memory_order_relaxed) ) {
  52. #if !defined(BOOST_FIBERS_SPIN_SINGLE_CORE)
  53. if ( max_relax_retries > retries) {
  54. ++retries;
  55. // give CPU a hint that this thread is in a "spin-wait" loop
  56. // delays the next instruction's execution for a finite period of time (depends on processor family)
  57. // the CPU is not under demand, parts of the pipeline are no longer being used
  58. // -> reduces the power consumed by the CPU
  59. // -> prevent pipeline stalls
  60. cpu_relax();
  61. } else if ( max_sleep_retries > retries) {
  62. ++retries;
  63. // std::this_thread::sleep_for( 0us) has a fairly long instruction path length,
  64. // combined with an expensive ring3 to ring 0 transition costing about 1000 cycles
  65. // std::this_thread::sleep_for( 0us) lets give up this_thread the remaining part of its time slice
  66. // if and only if a thread of equal or greater priority is ready to run
  67. static constexpr std::chrono::microseconds us0{ 0 };
  68. std::this_thread::sleep_for( us0);
  69. } else {
  70. // std::this_thread::yield() allows this_thread to give up the remaining part of its time slice,
  71. // but only to another thread on the same processor
  72. // instead of constant checking, a thread only checks if no other useful work is pending
  73. std::this_thread::yield();
  74. }
  75. #else
  76. std::this_thread::yield();
  77. #endif
  78. }
  79. // test-and-set shared variable 'status_'
  80. // everytime 'status_' is signaled over the bus, even if the test failes
  81. if ( spinlock_status::locked == state_.exchange( spinlock_status::locked, std::memory_order_acquire) ) {
  82. // spinlock now contended
  83. // utilize 'Binary Exponential Backoff' algorithm
  84. // linear_congruential_engine is a random number engine based on Linear congruential generator (LCG)
  85. std::uniform_int_distribution< std::size_t > distribution{
  86. 0, static_cast< std::size_t >( 1) << (std::min)(collisions, static_cast< std::size_t >( BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD)) };
  87. const std::size_t z = distribution( generator);
  88. ++collisions;
  89. for ( std::size_t i = 0; i < z; ++i) {
  90. // -> reduces the power consumed by the CPU
  91. // -> prevent pipeline stalls
  92. cpu_relax();
  93. }
  94. } else {
  95. retries_.store( prev_retries + (retries - prev_retries) / 8, std::memory_order_relaxed);
  96. // success, thread has acquired the lock
  97. break;
  98. }
  99. }
  100. }
  101. bool try_lock() noexcept {
  102. return spinlock_status::unlocked == state_.exchange( spinlock_status::locked, std::memory_order_acquire);
  103. }
  104. void unlock() noexcept {
  105. state_.store( spinlock_status::unlocked, std::memory_order_release);
  106. }
  107. };
  108. }}}
  109. #endif // BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_H