HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
wfree_idle_count.hpp
1// Copyright Take Vos 2022.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "../utility/utility.hpp"
8#include "../macros.hpp"
9#include <atomic>
10#include <cstdint>
11
12
13
14namespace hi::inline v1 {
15
41public:
42 constexpr wfree_idle_count() noexcept = default;
43 ~wfree_idle_count() = default;
44 wfree_idle_count(wfree_idle_count const&) = delete;
46 wfree_idle_count& operator=(wfree_idle_count const&) = delete;
47 wfree_idle_count& operator=(wfree_idle_count&&) = delete;
48
53 [[nodiscard]] hi_force_inline bool is_locked() const noexcept
54 {
55 return to_bool(_lock_count.load(std::memory_order::relaxed));
56 }
57
62 hi_force_inline void lock() noexcept
63 {
64 hilet lock_count = _lock_count.fetch_add(1, std::memory_order::acquire);
65 hi_axiom(lock_count != std::numeric_limits<uint32_t>::max());
66 }
67
72 hi_force_inline void unlock() noexcept
73 {
74 auto lock_count = _lock_count.fetch_sub(1, std::memory_order::release);
75 hi_axiom(lock_count != 0);
76 if (lock_count == 1) {
77 // No one is locking, increment the idle count.
78 _version.fetch_add(1, std::memory_order::relaxed);
79 }
80 }
81
86 hi_force_inline uint64_t operator*() const noexcept
87 {
88 return _version.load(std::memory_order::acquire);
89 }
90
91private:
92 std::atomic<uint64_t> _version = 0;
93 std::atomic<uint64_t> _lock_count = 0;
94};
95
96} // namespace hi::inline v1
DOXYGEN BUG.
Definition algorithm.hpp:16
constexpr Out narrow_cast(In const &rhs) noexcept
Cast numeric values without loss of precision.
Definition cast.hpp:377
Counts how many times a critical section was idle.
Definition wfree_idle_count.hpp:40
hi_force_inline void lock() noexcept
Start the critical section.
Definition wfree_idle_count.hpp:62
hi_force_inline bool is_locked() const noexcept
Check if the critical section is locked.
Definition wfree_idle_count.hpp:53
hi_force_inline uint64_t operator*() const noexcept
Get the current idle-count.
Definition wfree_idle_count.hpp:86
hi_force_inline void unlock() noexcept
End the critical section.
Definition wfree_idle_count.hpp:72