NIM 跨平台 C++ SDK
载入中...
搜索中...
未找到
ne_stl_spinlock.h
浏览该文件的文档.
1#ifndef NE_STL_INCLUDENE_STL_SPINLOCK_H
2#define NE_STL_INCLUDENE_STL_SPINLOCK_H
3
4#include "ne_stl_atomic.h"
5#include "ne_stl_build.h"
6#include "ne_stl_value_def.h"
7
8#define NE_STL_SPINLOCK_USE_THRD_YIELD 1
9#if (NE_STL_SPINLOCK_USE_THRD_YIELD)
10#ifdef NE_STL_OS_WIN
11#if defined(NE_STL_USE_MSVC)
12#if (_MSC_VER < 1920)
13#include <thr/xthreads.h>
14#else
15#include <xthreads.h>
16#endif
17#else
18#include <xthreads.h>
19#endif
20#define THRD_YIELD() _Thrd_yield()
21#else
22#if defined(NE_STL_OS_ANDROID) || defined(NE_STL_OS_LINUX)
23#include <sched.h>
24#define THRD_YIELD() sched_yield()
25#else
26#include <pthread.h>
27// #define THRD_YIELD() pthread_yield()
28#define THRD_YIELD() pthread_yield_np()
29#endif
30#endif
31#else
32#define THRD_YIELD()
33#endif
34namespace nstd {
35
36namespace {
37
38enum class lock_state : int32_t { lock_state_begin, lock_state_unlocked, lock_state_locked, lock_state_end };
39
40struct lock_locked : integral_constant<int32_t, static_cast<int32_t>(lock_state::lock_state_locked)> {};
41struct lock_unlocked : integral_constant<int32_t, static_cast<int32_t>(lock_state::lock_state_unlocked)> {};
42
43} // namespace
44class _spinlock {
45public:
47 : value_{lock_unlocked::value} {}
48 inline void lock() {
49 while (!value_.compare_exchange(lock_unlocked::value, lock_locked::value)) {
50 THRD_YIELD();
51 }
52 }
53 inline void unlock() { value_.store(lock_unlocked::value); }
54 _spinlock& operator=(const _spinlock& other) = delete;
55
56private:
58};
60
62public:
63 explicit _lock_guard(spinlock& lock)
64 : lock_(lock) {
65 lock_.lock();
66 }
68 _lock_guard& operator=(const _lock_guard& other) = delete;
69
70private:
72};
74
75} // namespace nstd
76
77#endif // NE_STL_INCLUDENE_STL_SPINLOCK_H
Definition ne_stl_spinlock.h:61
_lock_guard(spinlock &lock)
Definition ne_stl_spinlock.h:63
_lock_guard & operator=(const _lock_guard &other)=delete
~_lock_guard()
Definition ne_stl_spinlock.h:67
nstd::spinlock & lock_
Definition ne_stl_spinlock.h:71
Definition ne_stl_spinlock.h:44
nstd::atomic_int value_
Definition ne_stl_spinlock.h:57
void lock()
Definition ne_stl_spinlock.h:48
_spinlock & operator=(const _spinlock &other)=delete
_spinlock()
Definition ne_stl_spinlock.h:46
void unlock()
Definition ne_stl_spinlock.h:53
bool compare_exchange(const T expected_val, const T new_val)
Definition ne_stl_atomic.h:161
void store(const T new_val)
Definition ne_stl_atomic.h:174
Definition ne_stl_any.h:7
_integral_constant< T, _value > integral_constant
Definition ne_stl_type_traits.h:15
#define THRD_YIELD()
Definition ne_stl_spinlock.h:28