HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
ort_spin_lock.h
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License.
3 #pragma once
5 #include <atomic>
6 
7 namespace onnxruntime {
8 /*
9 OrtSpinLock implemented mutex semantic "lock-freely",
10 calling thread will not be put to sleep on blocked,
11 which reduces cpu usage on context switching.
12 */
13 struct OrtSpinLock {
14  using LockState = enum { Locked = 0,
15  Unlocked };
16 
17  void lock() noexcept {
18  LockState state = Unlocked;
19  while (!state_.compare_exchange_weak(state, Locked, std::memory_order_acq_rel, std::memory_order_relaxed)) {
20  state = Unlocked;
21  concurrency::SpinPause(); // pause and retry
22  }
23  }
24  bool try_lock() noexcept {
25  LockState state = Unlocked;
26  return state_.compare_exchange_weak(state, Locked, std::memory_order_acq_rel, std::memory_order_relaxed);
27  }
28  void unlock() noexcept {
29  state_.store(Unlocked, std::memory_order_release);
30  }
31 
32  private:
33  std::atomic<LockState> state_{Unlocked};
34 };
35 } // namespace onnxruntime
void lock() noexcept
Definition: ort_spin_lock.h:17
void unlock() noexcept
Definition: ort_spin_lock.h:28
bool try_lock() noexcept
Definition: ort_spin_lock.h:24
enum{Locked=0, Unlocked} LockState
Definition: ort_spin_lock.h:15