Introduce Spinlock class
authorMarco Costalba <mcostalba@gmail.com>
Sun, 22 Feb 2015 13:40:46 +0000 (14:40 +0100)
committerMarco Costalba <mcostalba@gmail.com>
Mon, 23 Feb 2015 12:37:46 +0000 (13:37 +0100)
Initialization is more complex than what I'd like due
to MSVC compatibility that for some reason does not like:

std::atomic_flag lock = ATOMIC_FLAG_INIT;

No functional change.

src/thread.h

index 606f962..166ea80 100644 (file)
@@ -20,6 +20,7 @@
 #ifndef THREAD_H_INCLUDED
 #define THREAD_H_INCLUDED
 
+#include <atomic>
 #include <bitset>
 #include <condition_variable>
 #include <mutex>
@@ -69,6 +70,19 @@ struct SplitPoint {
 };
 
 
+/// Spinlock class wraps low level atomic operations to provide spin lock functionality
+
+class Spinlock {
+
+  std::atomic_flag lock;
+
+public:
+  Spinlock() { std::atomic_flag_clear(&lock); }
+  void acquire() { while (lock.test_and_set(std::memory_order_acquire)) {} }
+  void release() { lock.clear(std::memory_order_release); }
+};
+
+
 /// ThreadBase struct is the base of the hierarchy from where we derive all the
 /// specialized thread classes.