Skip to content

Instantly share code, notes, and snippets.

@vovaprog
Created September 5, 2016 15:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vovaprog/71db1045d79ae3d47ce058040895cea2 to your computer and use it in GitHub Desktop.
Save vovaprog/71db1045d79ae3d47ce058040895cea2 to your computer and use it in GitHub Desktop.
simple c++ spinlock
#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
@plusangel
Copy link

plusangel commented Mar 11, 2020

I think that the lock() might be:

void lock() {
    while (flag.test_and_set(std::memory_order_acquire));
  } 

Thanks for the clean snippet though :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment