Created
May 15, 2013 08:31
-
-
Save aperezdc/5582452 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Spinlock based on Qt atomic operations. Should be fairly portable. | |
* To use it, it is recommended to use the SpinLock::Acquire helper | |
* class to follow RAII patterns, e.g.: | |
* | |
* static SpinLock g_myLock; | |
* // ... | |
* | |
* void foo() { | |
* do_seomething(); | |
* // Critical section is contained in a single code block. | |
* { | |
* SpinLock::Acquire locked(g_myLock); | |
* do_critical_stuff(); | |
* } | |
* do_more_stuff(); | |
* } | |
*/ | |
#ifndef SPINLOCK_HPP | |
#define SPINLOCK_HPP | |
#include <QAtomicInt> | |
class SpinLock: private QAtomicInt | |
{ | |
public: | |
class Acquire { | |
public: | |
Acquire(SpinLock& spinLock): m_spinLock(spinLock) | |
{ m_spinLock.lock(); } | |
~Acquire() | |
{ m_spinLock.unlock(); } | |
private: | |
SpinLock& m_spinLock; | |
// Disable copy constructor and assignment operator | |
Acquire& operator=(const Acquire&); | |
Acquire(const Acquire&); | |
}; | |
SpinLock(): QAtomicInt(Unlocked) {} | |
void lock() { | |
while (!testAndSetOrdered(Unlocked, Locked)); // Busy-wait | |
} | |
void unlock() { | |
while (!testAndSetOrdered(Locked, Unlocked)); // Busy-wait | |
} | |
bool tryLock() { | |
return testAndSetOrdered(Unlocked, Locked); | |
} | |
private: | |
static const int Unlocked = 1; | |
static const int Locked = 0; | |
}; | |
#endif /* !SPINLOCK_HPP */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment