spinlock_ttas_adaptive_futex.hpp 6.5 KB

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