Jamba C++ API 7.5.0
Loading...
Searching...
No Matches
SpinLock.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2018 pongasoft
3 *
4 * Licensed under the Apache License, Version 2.0 or the MIT license,
5 * at your option. You may not use this file except in compliance with
6 * one of these licenses. You may obtain copies of the licenses at:
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 * https://opensource.org/licenses/MIT
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 * License for the specific language governing permissions and limitations under
15 * the License.
16 *
17 * @author Yan Pujante
18 */
19
20#pragma once
21
22#include <atomic>
23
34{
35public:
36
37 class Lock
38 {
39 public:
43 inline ~Lock()
44 {
45 if(fSpinLock != nullptr)
46 fSpinLock->unlock();
47 }
48
49 inline Lock(Lock &&iLock) noexcept : fSpinLock{iLock.fSpinLock}
50 {
51 iLock.fSpinLock = nullptr;
52 }
53
54 Lock(Lock const &) = delete;
55 Lock& operator=(Lock const &) = delete;
56
57 private:
58 friend class SpinLock;
59
60 explicit Lock(SpinLock *iSpinLock) : fSpinLock{iSpinLock}
61 {
62 }
63
64
66 };
67
68 SpinLock() : fFlag{false}
69 {
70 }
71
75 inline Lock acquire()
76 {
77 while(fFlag.test_and_set(std::memory_order_acquire))
78 {
79 // nothing to do => spin
80 }
81
82 return Lock(this);
83 }
84
85
86 SpinLock(SpinLock const &) = delete;
87
88 SpinLock &operator=(SpinLock const &) = delete;
89
90private:
91 friend class Lock;
92
93 inline void unlock()
94 {
95 fFlag.clear(std::memory_order_release);
96 }
97
98 std::atomic_flag fFlag;
99};
Definition SpinLock.h:38
Lock(Lock &&iLock) noexcept
Definition SpinLock.h:49
friend class SpinLock
Definition SpinLock.h:58
Lock & operator=(Lock const &)=delete
SpinLock * fSpinLock
Definition SpinLock.h:65
Lock(SpinLock *iSpinLock)
Definition SpinLock.h:60
~Lock()
This will automatically release the lock.
Definition SpinLock.h:43
Lock(Lock const &)=delete
SpinLock()
Definition SpinLock.h:68
friend class Lock
Definition SpinLock.h:91
Lock acquire()
Definition SpinLock.h:75
void unlock()
Definition SpinLock.h:93
SpinLock & operator=(SpinLock const &)=delete
SpinLock(SpinLock const &)=delete
std::atomic_flag fFlag
Definition SpinLock.h:98