SimpleAI
 All Classes Namespaces Files Functions Variables Typedefs Macros Groups Pages
Thread.h
Go to the documentation of this file.
1 
4 #pragma once
5 
6 #include "Types.h"
7 #include <thread>
8 #include <mutex>
9 #include <atomic>
10 
11 namespace ai {
12 
13 // TODO: not a real read-write-lock - maybe someday
15 private:
16  const std::string _name;
17  mutable std::atomic_flag _locked = ATOMIC_FLAG_INIT;
18 public:
19  ReadWriteLock(const std::string& name) :
20  _name(name) {
21  }
22 
23  inline void lockRead() const {
24  while (_locked.test_and_set(std::memory_order_acquire)) {
25  std::this_thread::yield();
26  }
27  }
28 
29  inline void unlockRead() const {
30  _locked.clear(std::memory_order_release);
31  }
32 
33  inline void lockWrite() {
34  while (_locked.test_and_set(std::memory_order_acquire)) {
35  std::this_thread::yield();
36  }
37  }
38 
39  inline void unlockWrite() {
40  _locked.clear(std::memory_order_release);
41  }
42 };
43 
45 private:
46  const ReadWriteLock& _lock;
47 public:
48  explicit ScopedReadLock(const ReadWriteLock& lock) : _lock(lock) {
49  _lock.lockRead();
50  }
51  ~ScopedReadLock() {
52  _lock.unlockRead();
53  }
54 };
55 
57 private:
58  ReadWriteLock& _lock;
59 public:
60  explicit ScopedWriteLock(ReadWriteLock& lock) : _lock(lock) {
61  _lock.lockWrite();
62  }
63  ~ScopedWriteLock() {
64  _lock.unlockWrite();
65  }
66 };
67 
68 #ifndef AI_THREAD_LOCAL
69 #define AI_THREAD_LOCAL thread_local
70 #endif
71 
72 }
Definition: Thread.h:44
Definition: Thread.h:56
Definition: Thread.h:14