| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "compat/gsl14.hpp" | ||
| 2 | #ifndef NDEBUG | ||
| 3 | #include <cassert> | ||
| 4 | #include <thread> | ||
| 5 | #endif // NDEBUG | ||
| 6 | |||
| 7 | // See https://en.cppreference.com/w/cpp/named_req/BasicLockable | ||
| 8 | template <typename T> | ||
| 9 | class BasicLockable { | ||
| 10 | public: | ||
| 11 | void lock(); | ||
| 12 | void unlock(); | ||
| 13 | void assert_ownership() const; | ||
| 14 | [[nodiscard]] bool this_thread_is_owner() const; | ||
| 15 | |||
| 16 | private: | ||
| 17 | #ifndef NDEBUG | ||
| 18 | static const std::thread::id none_; // initialized later | ||
| 19 | std::thread::id owner_{none_}; // initially unowned | ||
| 20 | #endif // NDEBUG | ||
| 21 | T lock_{}; // initially unlocked | ||
| 22 | }; | ||
| 23 | |||
| 24 | //////////////////////////////////////////////////////////////////////////////// | ||
| 25 | |||
| 26 | template <typename T> | ||
| 27 | 200002 | void BasicLockable<T>::lock() { | |
| 28 | 200002 | lock_.lock(); | |
| 29 | #ifndef NDEBUG | ||
| 30 | 200002 | owner_ = std::this_thread::get_id(); | |
| 31 | #endif // NDEBUG | ||
| 32 | 200002 | } | |
| 33 | |||
| 34 | template <typename T> | ||
| 35 | 200002 | void BasicLockable<T>::unlock() { | |
| 36 | #ifndef NDEBUG | ||
| 37 | 200002 | owner_ = none_; | |
| 38 | #endif // NDEBUG | ||
| 39 | 200002 | lock_.unlock(); | |
| 40 | 200002 | } | |
| 41 | |||
| 42 | template <typename T> | ||
| 43 | 100002 | void BasicLockable<T>::assert_ownership() const { | |
| 44 | #ifdef NDEBUG | ||
| 45 | // never fails for RELEASE build | ||
| 46 | #else | ||
| 47 |
1/2✓ Branch 3 taken 100002 times.
✗ Branch 4 not taken.
|
100002 | assert((owner_ == std::this_thread::get_id()) |
| 48 | && "Lock should be owned by this thread"); | ||
| 49 | #endif // NDEBUG | ||
| 50 | 100002 | } | |
| 51 | |||
| 52 | template <typename T> | ||
| 53 | 100000 | bool BasicLockable<T>::this_thread_is_owner() const { | |
| 54 | #ifdef NDEBUG | ||
| 55 | return true; // never fails for RELEASE build | ||
| 56 | #else | ||
| 57 | 100000 | return std::this_thread::get_id() == owner_; | |
| 58 | #endif // NDEBUG | ||
| 59 | } | ||
| 60 | |||
| 61 | #ifndef NDEBUG | ||
| 62 | template <typename T> | ||
| 63 | const std::thread::id BasicLockable<T>::none_{}; | ||
| 64 | #endif // NDEBUG | ||
| 65 |