github.com/igggame/nebulas-go@v2.1.0+incompatible/nbre/3rd_party/fflib/include/ff/functionflow/utilities/spin_lock.h (about)

     1  /***********************************************
     2  The MIT License (MIT)
     3  
     4  Copyright (c) 2012 Athrun Arthur <athrunarthur@gmail.com>
     5  
     6  Permission is hereby granted, free of charge, to any person obtaining a copy
     7  of this software and associated documentation files (the "Software"), to deal
     8  in the Software without restriction, including without limitation the rights
     9  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    10  copies of the Software, and to permit persons to whom the Software is
    11  furnished to do so, subject to the following conditions:
    12  
    13  The above copyright notice and this permission notice shall be included in
    14  all copies or substantial portions of the Software.
    15  
    16  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    17  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    18  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    19  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    20  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    21  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    22  THE SOFTWARE.
    23  *************************************************/
    24  #ifndef FF_COMMON_SPIN_LOCK_H_
    25  #define FF_COMMON_SPIN_LOCK_H_
    26  #include "ff/functionflow/common/common.h"
    27  #include "ff/functionflow/runtime/rtcmn.h"
    28  
    29  #pragma GCC diagnostic push
    30  #pragma GCC diagnostic ignored "-Wbraced-scalar-init"
    31  
    32  namespace ff {
    33  class spinlock {
    34    std::atomic_flag flag;
    35  
    36   public:
    37    spinlock() : flag(ATOMIC_FLAG_INIT) {}
    38  
    39    spinlock(const spinlock &) = delete;
    40    spinlock &operator=(const spinlock &) = delete;
    41  
    42    inline void lock() {
    43      while (!flag.test_and_set(std::memory_order_acquire))
    44        std::this_thread::yield();
    45    }
    46  
    47    inline bool try_lock() {
    48      return !flag.test_and_set(std::memory_order_acquire);
    49    }
    50    inline void unlock() { flag.clear(std::memory_order_release); }
    51  };  // end class spin_lock
    52  }  // end namespace ff
    53  
    54  #pragma GCC diagnostic pop
    55  #endif