File indexing completed on 2025-01-30 09:35:34
0001
0002
0003
0004
0005
0006
0007 #ifndef BOOST_FIBERS_SPINLOCK_TTAS_H
0008 #define BOOST_FIBERS_SPINLOCK_TTAS_H
0009
0010 #include <algorithm>
0011 #include <atomic>
0012 #include <chrono>
0013 #include <cmath>
0014 #include <random>
0015 #include <thread>
0016
0017 #include <boost/fiber/detail/config.hpp>
0018 #include <boost/fiber/detail/cpu_relax.hpp>
0019 #include <boost/fiber/detail/spinlock_status.hpp>
0020
0021
0022
0023
0024
0025 namespace boost {
0026 namespace fibers {
0027 namespace detail {
0028
0029 class spinlock_ttas {
0030 private:
0031 template< typename FBSplk >
0032 friend class spinlock_rtm;
0033
0034 std::atomic< spinlock_status > state_{ spinlock_status::unlocked };
0035
0036 public:
0037 spinlock_ttas() = default;
0038
0039 spinlock_ttas( spinlock_ttas const&) = delete;
0040 spinlock_ttas & operator=( spinlock_ttas const&) = delete;
0041
0042 void lock() noexcept {
0043 static thread_local std::minstd_rand generator{ std::random_device{}() };
0044 std::size_t collisions = 0 ;
0045 for (;;) {
0046
0047
0048
0049
0050
0051 std::size_t retries = 0;
0052
0053
0054
0055
0056
0057 while ( spinlock_status::locked == state_.load( std::memory_order_relaxed) ) {
0058 #if !defined(BOOST_FIBERS_SPIN_SINGLE_CORE)
0059 if ( BOOST_FIBERS_SPIN_BEFORE_SLEEP0 > retries) {
0060 ++retries;
0061
0062
0063
0064
0065
0066 cpu_relax();
0067 } else if ( BOOST_FIBERS_SPIN_BEFORE_YIELD > retries) {
0068 ++retries;
0069
0070
0071
0072
0073 static constexpr std::chrono::microseconds us0{ 0 };
0074 std::this_thread::sleep_for( us0);
0075 } else {
0076
0077
0078
0079 std::this_thread::yield();
0080 }
0081 #else
0082 std::this_thread::yield();
0083 #endif
0084 }
0085
0086
0087 if ( spinlock_status::locked == state_.exchange( spinlock_status::locked, std::memory_order_acquire) ) {
0088
0089
0090
0091 std::uniform_int_distribution< std::size_t > distribution{
0092 0, static_cast< std::size_t >( 1) << (std::min)(collisions, static_cast< std::size_t >( BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD)) };
0093 const std::size_t z = distribution( generator);
0094 ++collisions;
0095 for ( std::size_t i = 0; i < z; ++i) {
0096
0097
0098 cpu_relax();
0099 }
0100 } else {
0101
0102 break;
0103 }
0104 }
0105 }
0106
0107 bool try_lock() noexcept {
0108 return spinlock_status::unlocked == state_.exchange( spinlock_status::locked, std::memory_order_acquire);
0109 }
0110
0111 void unlock() noexcept {
0112 state_.store( spinlock_status::unlocked, std::memory_order_release);
0113 }
0114 };
0115
0116 }}}
0117
0118 #endif