Jamba C++ API 8.0.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:
44 {
45 if(fSpinLock != nullptr)
46 fSpinLock->unlock();
47 }
48
49 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() = default;
69
74 {
75 while(fFlag.test_and_set(std::memory_order_acquire))
76 {
77 // nothing to do => spin
78 }
79
80 return Lock(this);
81 }
82
83
84 SpinLock(SpinLock const &) = delete;
85
86 SpinLock &operator=(SpinLock const &) = delete;
87
88private:
89 friend class Lock;
90
91 void unlock()
92 {
93 fFlag.clear(std::memory_order_release);
94 }
95
96 std::atomic_flag fFlag;
97};
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
friend class Lock
Definition SpinLock.h:89
Lock acquire()
Definition SpinLock.h:73
void unlock()
Definition SpinLock.h:91
SpinLock & operator=(SpinLock const &)=delete
SpinLock(SpinLock const &)=delete
SpinLock()=default
std::atomic_flag fFlag
Definition SpinLock.h:96