Skip to content

Instantly share code, notes, and snippets.

@stephentu
Created June 23, 2015 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephentu/970ad6972be1043cbbb7 to your computer and use it in GitHub Desktop.
Save stephentu/970ad6972be1043cbbb7 to your computer and use it in GitHub Desktop.
#pragma once
#include <atomic>
#include <cyclades/macros.hpp>
namespace cyclades {
// implements Lockable concept (C++11)
class spinlock {
public:
spinlock() : flag_(false) {}
// non-copyable/non-movable
spinlock(const spinlock &) = delete;
spinlock(spinlock &&) = delete;
spinlock &operator=(const spinlock &) = delete;
inline void
lock()
{
while (flag_.exchange(true, std::memory_order_acquire))
nop_pause();
}
inline void
unlock()
{
flag_.store(false, std::memory_order_release);
}
inline bool
try_lock()
{
return !flag_.exchange(true, std::memory_order_acquire);
}
private:
std::atomic<bool> flag_;
};
} // namespace cyclades
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment