GemaCoreLib
The GeMA Core library
gmSpinLock.h
Go to the documentation of this file.
1 /************************************************************************
2 **
3 ** Copyright (C) 2014 by Carlos Augusto Teixera Mendes
4 ** All rights reserved.
5 **
6 ** This file is part of the "GeMA" software. It's use should respect
7 ** the terms in the license agreement that can be found together
8 ** with this source code.
9 ** It is provided AS IS, with NO WARRANTY OF ANY KIND,
10 ** INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR
11 ** A PARTICULAR PURPOSE.
12 **
13 ************************************************************************/
14 
24 #ifndef _GEMA_SPIN_LOCK_H_
25 #define _GEMA_SPIN_LOCK_H_
26 
27 #include <QAtomicInteger>
28 
36 class GmSpinLock : public QAtomicInt
37 {
38 public:
41 
43  void lock() { while(!testAndSetAcquire(0, 1)); }
44 
46  bool tryLock() { return testAndSetAcquire(0, 1); }
47 
49  void unlock() { storeRelease(0); }
50 };
51 
54 {
55 public:
57  GmSpinLocker(GmSpinLock& lock) : _lock(lock) { _lock.lock(); }
58 
61 
62 private:
64 };
65 
66 #endif
A simple spin lock implementation based on a loop using test and set over an atomic int to change its...
Definition: gmSpinLock.h:36
GmSpinLock & _lock
The spin lock object.
Definition: gmSpinLock.h:63
RAII object used to acquire a spin lock and release it upon object destruction.
Definition: gmSpinLock.h:53
bool testAndSetAcquire(T expectedValue, T newValue)
bool tryLock()
Try to lock. Returns true if the lock was aquired, false otherwise.
Definition: gmSpinLock.h:46
GmSpinLock()
Constructor.
Definition: gmSpinLock.h:40
void storeRelease(T newValue)
~GmSpinLocker()
Destructo. Releases the lock.
Definition: gmSpinLock.h:60
GmSpinLocker(GmSpinLock &lock)
Constructor. Acquires the lock.
Definition: gmSpinLock.h:57
void unlock()
Releases the lock.
Definition: gmSpinLock.h:49
void lock()
Aquires the lock.
Definition: gmSpinLock.h:43