Created
June 23, 2015 17:41
-
-
Save stephentu/970ad6972be1043cbbb7 to your computer and use it in GitHub Desktop.
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
#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