spinlock_ttas_futex.hpp 5.8 KB

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