All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
spinMutex.h
1//
2// Copyright 2023 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_TF_SPIN_MUTEX_H
8#define PXR_BASE_TF_SPIN_MUTEX_H
9
10#include "pxr/pxr.h"
11#include "pxr/base/tf/api.h"
12
13#include "pxr/base/arch/hints.h"
15
16#include <atomic>
17
18PXR_NAMESPACE_OPEN_SCOPE
19
42{
43public:
44
46 TfSpinMutex() : _lockState(false) {}
47
50 struct ScopedLock {
51
54 : _mutex(&m)
55 , _acquired(false) {
56 Acquire();
57 }
58
60 ScopedLock() : _mutex(nullptr), _acquired(false) {}
61
64 Release();
65 }
66
70 Release();
71 _mutex = &m;
72 Acquire();
73 }
74
77 void Release() {
78 if (_acquired) {
79 _Release();
80 }
81 }
82
85 void Acquire() {
86 TF_DEV_AXIOM(!_acquired);
87 _mutex->Acquire();
88 _acquired = true;
89 }
90
91 private:
92
93 void _Release() {
94 TF_DEV_AXIOM(_acquired);
95 _mutex->Release();
96 _acquired = false;
97 }
98
99 TfSpinMutex *_mutex;
100 bool _acquired;
101 };
102
107 inline bool TryAcquire() {
108 return _lockState.exchange(true, std::memory_order_acquire) == false;
109 }
110
114 void Acquire() {
115 if (ARCH_LIKELY(TryAcquire())) {
116 return;
117 }
118 _AcquireContended();
119 }
120
122 inline void Release() {
123 _lockState.store(false, std::memory_order_release);
124 }
125
126private:
127
128 TF_API void _AcquireContended();
129
130 std::atomic<bool> _lockState;
131};
132
133PXR_NAMESPACE_CLOSE_SCOPE
134
135#endif // PXR_BASE_TF_SPIN_MUTEX_H
This class implements a simple spin lock that emphasizes throughput when there is little to no conten...
Definition: spinMutex.h:42
TfSpinMutex()
Construct a mutex, initially unlocked.
Definition: spinMutex.h:46
void Release()
Release this thread's lock on this mutex.
Definition: spinMutex.h:122
void Acquire()
Acquire a lock on this mutex.
Definition: spinMutex.h:114
bool TryAcquire()
Acquire a lock on this mutex if it is not currently held by another thread.
Definition: spinMutex.h:107
Stripped down version of diagnostic.h that doesn't define std::string.
#define TF_DEV_AXIOM(cond)
The same as TF_AXIOM, but compiled only in dev builds.
Definition: diagnostic.h:205
Compiler hints.
Scoped lock utility class.
Definition: spinMutex.h:50
ScopedLock()
Construct a scoped lock not associated with a mutex.
Definition: spinMutex.h:60
void Acquire(TfSpinMutex &m)
If the current scoped lock is acquired, Release() it, then associate this lock with m and acquire a l...
Definition: spinMutex.h:69
void Release()
Release the currently required lock on the associated mutex.
Definition: spinMutex.h:77
ScopedLock(TfSpinMutex &m)
Construct a scoped lock for mutex m and acquire a lock.
Definition: spinMutex.h:53
void Acquire()
Acquire a lock on this lock's associated mutex.
Definition: spinMutex.h:85
~ScopedLock()
If this scoped lock is acquired, Release() it.
Definition: spinMutex.h:63