0d9a357373
This commit introduce three new `til` features: * "til/latch.h": A std::latch clone, until we're on C++20. * "til/mutex.h": A safe mutex wrapper, which only allows you access to the protected data after locking it. No more forgetting to lock mutexes! * "til/throttled_func.h": Function invocation throttling used to be available as the `ThrottledFunc` class already. But this class is vastly more efficient and doesn't rely on any WinRT types. This PR also adds a `til::ends_with` string helper which is `til::starts_with` counterpart. ## Validation Steps Performed * Scrollbar throttling still works as it used to ✔️ * No performance regressions when printing big.txt ✔️ Closes #10393
87 lines
2 KiB
C++
87 lines
2 KiB
C++
// Copyright (c) Microsoft Corporation.
|
|
// Licensed under the MIT license.
|
|
|
|
#pragma once
|
|
|
|
#ifdef __cpp_lib_latch
|
|
#include <latch>
|
|
#endif
|
|
|
|
namespace til
|
|
{
|
|
#ifdef __cpp_lib_latch
|
|
using latch = std::latch;
|
|
#else
|
|
class latch
|
|
{
|
|
public:
|
|
[[nodiscard]] static constexpr ptrdiff_t max() noexcept
|
|
{
|
|
return std::numeric_limits<ptrdiff_t>::max();
|
|
}
|
|
|
|
constexpr explicit latch(const ptrdiff_t expected) noexcept :
|
|
counter{ expected }
|
|
{
|
|
assert(expected >= 0);
|
|
}
|
|
|
|
latch(const latch&) = delete;
|
|
latch& operator=(const latch&) = delete;
|
|
|
|
void count_down(const ptrdiff_t n = 1) noexcept
|
|
{
|
|
assert(n >= 0);
|
|
|
|
const auto old = counter.fetch_sub(n, std::memory_order_release);
|
|
if (old == n)
|
|
{
|
|
WakeByAddressAll(&counter);
|
|
return;
|
|
}
|
|
|
|
assert(old > n);
|
|
}
|
|
|
|
[[nodiscard]] bool try_wait() const noexcept
|
|
{
|
|
return counter.load(std::memory_order_acquire) == 0;
|
|
}
|
|
|
|
void wait() const noexcept
|
|
{
|
|
while (true)
|
|
{
|
|
auto current = counter.load(std::memory_order_acquire);
|
|
if (current == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
assert(current > 0);
|
|
WaitOnAddress(const_cast<decltype(counter)*>(&counter), ¤t, sizeof(counter), INFINITE);
|
|
}
|
|
}
|
|
|
|
void arrive_and_wait(const ptrdiff_t n = 1) noexcept
|
|
{
|
|
assert(n >= 0);
|
|
|
|
auto old = counter.fetch_sub(n, std::memory_order_acq_rel);
|
|
if (old == n)
|
|
{
|
|
WakeByAddressAll(&counter);
|
|
return;
|
|
}
|
|
|
|
assert(old > n);
|
|
WaitOnAddress(&counter, &old, sizeof(counter), INFINITE);
|
|
wait();
|
|
}
|
|
|
|
private:
|
|
std::atomic<ptrdiff_t> counter;
|
|
};
|
|
#endif
|
|
}
|