TPIE

11a2c2d
spin_lock.h
1 // -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
2 // vi:set ts=4 sts=4 sw=4 noet :
3 //
4 // Copyright 2017, The TPIE development team
5 //
6 // This file is part of TPIE.
7 //
8 // TPIE is free software: you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License as published by the
10 // Free Software Foundation, either version 3 of the License, or (at your
11 // option) any later version.
12 //
13 // TPIE is distributed in the hope that it will be useful, but WITHOUT ANY
14 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
16 // License for more details.
17 //
18 // You should have received a copy of the GNU Lesser General Public License
19 // along with TPIE. If not, see <http://www.gnu.org/licenses/>
20 
24 
25 #ifndef __TPIE_SPIN_LOCK_H__
26 #define __TPIE_SPIN_LOCK_H__
27 
28 #include <atomic>
29 #include <limits>
30 
31 namespace tpie {
32 
34 public:
35  unique_spin_lock(std::atomic_size_t & spin): spin(spin) {
36  while (true) {
37  size_t expected = 0;
38  if (spin.compare_exchange_weak(expected, 0x80000000)) return;
39  }
40  }
41  ~unique_spin_lock() {
42  spin -= 0x80000000;
43  }
44 private:
45  std::atomic_size_t & spin;
46 };
47 
48 
50 public:
51  shared_spin_lock(std::atomic_size_t & spin): spin(spin), locked(false) {
52  acquire();
53  }
54  void release() {
55  --spin;
56  locked = false;
57  }
58 
59  void acquire() {
60  spin++;
61  while (spin.load() >= 0x80000000) {}
62  locked = true;
63  }
64 
65  ~shared_spin_lock() {
66  if (locked) release();
67  }
68 private:
69  std::atomic_size_t & spin;
70  bool locked;
71 };
72 
73 } //namespace tpie
74 #endif //__TPIE_SPIN_LOCK_H__
tpie::shared_spin_lock
Definition: spin_lock.h:49
tpie::unique_spin_lock
Definition: spin_lock.h:33
tpie
Definition: access_type.h:26