Jamba C++ API  4.1.0
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 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  *
16  * @author Yan Pujante
17  */
18 
19 #pragma once
20 
21 #include <atomic>
22 
32 class SpinLock
33 {
34 public:
35 
36  class Lock
37  {
38  public:
42  inline ~Lock()
43  {
44  if(fSpinLock != nullptr)
45  fSpinLock->unlock();
46  }
47 
48  inline Lock(Lock &&iLock) noexcept : fSpinLock{iLock.fSpinLock}
49  {
50  iLock.fSpinLock = nullptr;
51  }
52 
53  Lock(Lock const &) = delete;
54  Lock& operator=(Lock const &) = delete;
55 
56  private:
57  friend class SpinLock;
58 
59  explicit Lock(SpinLock *iSpinLock) : fSpinLock{iSpinLock}
60  {
61  }
62 
63 
65  };
66 
67  SpinLock() : fFlag{false}
68  {
69  }
70 
74  inline Lock acquire()
75  {
76  while(fFlag.test_and_set(std::memory_order_acquire))
77  {
78  // nothing to do => spin
79  }
80 
81  return Lock(this);
82  }
83 
84 
85  SpinLock(SpinLock const &) = delete;
86 
87  SpinLock &operator=(SpinLock const &) = delete;
88 
89 private:
90  friend class Lock;
91 
92  inline void unlock()
93  {
94  fFlag.clear(std::memory_order_release);
95  }
96 
97  std::atomic_flag fFlag;
98 };
A simple implementation of a spin lock using the std::atomic_flag which is guaranteed to be atomic an...
Definition: SpinLock.h:32
SpinLock & operator=(SpinLock const &)=delete
friend class Lock
Definition: SpinLock.h:90
Lock(SpinLock *iSpinLock)
Definition: SpinLock.h:59
Lock acquire()
Definition: SpinLock.h:74
Lock & operator=(Lock const &)=delete
SpinLock()
Definition: SpinLock.h:67
SpinLock * fSpinLock
Definition: SpinLock.h:64
Lock(Lock &&iLock) noexcept
Definition: SpinLock.h:48
~Lock()
This will automatically release the lock.
Definition: SpinLock.h:42
void unlock()
Definition: SpinLock.h:92
Definition: SpinLock.h:36
std::atomic_flag fFlag
Definition: SpinLock.h:97