Created
September 5, 2016 15:06
-
-
Save vovaprog/71db1045d79ae3d47ce058040895cea2 to your computer and use it in GitHub Desktop.
simple c++ spinlock
This file contains 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
#ifndef SIMPLE_SPINLOCK_H | |
#define SIMPLE_SPINLOCK_H | |
#include <atomic> | |
class Spinlock | |
{ | |
public: | |
Spinlock() | |
{ | |
flag.clear(); | |
} | |
Spinlock(const Spinlock &tm) = delete; | |
Spinlock(Spinlock &&tm) = delete; | |
Spinlock& operator=(const Spinlock &tm) = delete; | |
Spinlock& operator=(Spinlock && tm) = delete; | |
void lock() | |
{ | |
while(!flag.test_and_set(std::memory_order_acquire)) { } | |
} | |
bool tryLock() | |
{ | |
return flag.test_and_set(std::memory_order_acquire) == false; | |
} | |
void unlock() | |
{ | |
flag.clear(std::memory_order_release); | |
} | |
private: | |
std::atomic_flag flag; | |
}; | |
#endif // SIMPLE_SPINLOCK_H | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think that the lock() might be:
Thanks for the clean snippet though :)