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 void 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 void
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;
91
92 // Otherwise, enter the spin to exchange the thread id to ours
94 {
95 Thread::YieldThread();
96 }
97}
98
99//------------------------------------------------------------------------------
102inline void
108
110{
112 : lock(lock)
113 {
114 this->lock->Lock();
115 }
117 {
118 this->lock->Unlock();
119 this->lock = nullptr;
120 }
121
123};
124
125} // namespace Threading
Definition spinlock.h:21
void Lock()
Lock.
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:103
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
Definition spinlock.h:110
SpinlockScope(Threading::Spinlock *lock)
Definition spinlock.h:111
~SpinlockScope()
Definition spinlock.h:116
Threading::Spinlock * lock
Definition spinlock.h:122