Nebula
Loading...
Searching...
No Matches
spinlock.h
Go to the documentation of this file.
1#pragma once
2//------------------------------------------------------------------------------
14//------------------------------------------------------------------------------
16#include "threading/thread.h"
17namespace Threading
18{
19
21{
22public:
24 Spinlock();
26 ~Spinlock();
27
29 void operator=(Spinlock&& rhs);
30
32 bool Lock();
34 void Unlock();
35private:
37};
38
39//------------------------------------------------------------------------------
42inline
47
48//------------------------------------------------------------------------------
51inline
53{
54 // Make sure this thread has the lock before we
55 this->Lock();
56 this->lock = InvalidThreadId;
57}
58
59//------------------------------------------------------------------------------
62inline void
64{
65 rhs.Lock();
66 rhs.lock = InvalidThreadId;
67
68 // If this wasn't locked when assigned, early out
69 if (InvalidThreadId == this->lock)
70 return;
71
72 // Lock this thread until whoever is holding it returns the lock
74 {
75 Thread::YieldThread();
76 }
77}
78
79//------------------------------------------------------------------------------
82inline bool
84{
85 // Attempt to set the lock, if already 1, yield the thread
86 ThreadId threadId = Thread::GetMyThreadId();
87
88 // If this thread already owns the spinlock, return early
89 if (threadId == this->lock)
90 return false;
91
92 // Otherwise, enter the spin to exchange the thread id to ours
94 {
95 Thread::YieldThread();
96 }
97
98 return true;
99}
100
101//------------------------------------------------------------------------------
104inline void
110
112{
114 : lock(lock)
115 {
116 this->lock->Lock();
117 }
119 {
120 this->lock->Unlock();
121 this->lock = nullptr;
122 }
123
125};
126
127} // namespace Threading
Definition spinlock.h:21
bool Lock()
Lock, returns true if it locked.
Definition spinlock.h:83
Spinlock()
Constructor.
Definition spinlock.h:43
volatile Threading::ThreadId lock
Definition spinlock.h:36
~Spinlock()
Destructor.
Definition spinlock.h:52
void Unlock()
Unlock.
Definition spinlock.h:105
void operator=(Spinlock &&rhs)
Move operator.
Definition spinlock.h:63
#define n_assert(exp)
Definition debug.h:50
int Exchange(int volatile *dest, int value)
interlocked exchange
Definition gccinterlocked.cc:94
int CompareExchange(int volatile *dest, int exchange, int comparand)
interlocked compare-exchange
Definition gccinterlocked.cc:112
The Jobs2 system provides a set of threads and a pool of jobs from which threads can pickup work.
Definition jobs2.h:16
static const ThreadId InvalidThreadId
Definition linuxthreadid.h:16
pthread_t ThreadId
Definition linuxthreadid.h:15
int64_t ThreadIdStorage
Definition linuxthreadid.h:17
SpinlockScope(Threading::Spinlock *lock)
Definition spinlock.h:113
~SpinlockScope()
Definition spinlock.h:118
Threading::Spinlock * lock
Definition spinlock.h:124