no way to compare when less than two revisions
Differences
This shows you the differences between two versions of the page.
— | blog:2019:0104_spinlock_implementation [2020/07/10 12:11] (current) – created - external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== SpinLock implementation in C++ ====== | ||
+ | {{tag> | ||
+ | |||
+ | Since I read the book **Game Engine Architecture** I was looking for a way to implement a simple **SpinLock** in C++. And actually it turns out this is (almost) readily available from boost. | ||
+ | |||
+ | ====== ====== | ||
+ | |||
+ | I used the following reference pages: | ||
+ | |||
+ | * [[https:// | ||
+ | * [[https:// | ||
+ | * [[https:// | ||
+ | |||
+ | |||
+ | And in the end, if will fit in a single simple header file: <sxh cpp># | ||
+ | #define NV_SPINLOCK_H_ | ||
+ | |||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | namespace nv { | ||
+ | |||
+ | class SpinLock | ||
+ | { | ||
+ | boost:: | ||
+ | // does not require ATOMIC_FLAG_INIT | ||
+ | public: | ||
+ | void lock() | ||
+ | { | ||
+ | while( flag.test_and_set(boost:: | ||
+ | ; | ||
+ | } | ||
+ | bool try_lock() | ||
+ | { | ||
+ | return !flag.test_and_set(boost:: | ||
+ | } | ||
+ | void unlock() | ||
+ | { | ||
+ | flag.clear(boost:: | ||
+ | } | ||
+ | }; | ||
+ | |||
+ | typedef boost:: | ||
+ | |||
+ | }; | ||
+ | |||
+ | # |