Hybrid ICN (hICN) plugin  v21.06-rc0-4-g18fa668
spinlock.h
1 /*
2  * Copyright (c) 2017-2019 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #pragma once
17 
18 #include <atomic>
19 
20 namespace utils {
21 
22 class SpinLock : private std::atomic_flag {
23  public:
24  class Acquire {
25  public:
26  Acquire(SpinLock& spin_lock) : spin_lock_(spin_lock) { spin_lock_.lock(); }
27 
28  ~Acquire() { spin_lock_.unlock(); }
29 
30  // No copies
31  Acquire& operator=(const Acquire&) = delete;
32  Acquire(const Acquire&) = delete;
33 
34  private:
35  SpinLock& spin_lock_;
36  };
37 
38  SpinLock() { clear(); }
39 
40  void lock() {
41  // busy-wait
42  while (std::atomic_flag::test_and_set(std::memory_order_acquire))
43  ;
44  }
45 
46  void unlock() { clear(std::memory_order_release); }
47 
48  bool tryLock() {
49  return std::atomic_flag::test_and_set(std::memory_order_acquire);
50  }
51 };
52 
53 } // namespace utils
utils::SpinLock
Definition: spinlock.h:22
utils::SpinLock::Acquire
Definition: spinlock.h:24