Loading...
Searching...
No Matches
Lock.h
Go to the documentation of this file.
1/**************************************************************************************************
2 * This file is a part of Ultralight. *
3 * *
4 * See <https://ultralig.ht> for licensing and more. *
5 * *
6 * (C) 2024 Ultralight, Inc. *
7 **************************************************************************************************/
8#pragma once
10#include <atomic>
11#include <mutex> // for std::lock_guard<>
12
13namespace ultralight {
14
15///
16/// Tiny, efficient spinlock that is optimized for short locking periods but will still
17/// intelligently yield the current thread and save CPU if the lock is held longer.
18///
19/// Can be used in place of std::mutex since it implements the STL's Lockable interface.
20///
21class Lock {
22 public:
23 constexpr Lock() = default;
24
25 UL_ALWAYS_INLINE void lock() noexcept {
26 // Optimistically assume the lock is free on the first try
27 if (!lock_.exchange(true, std::memory_order_acquire))
28 return;
29
31 }
32
33 UL_ALWAYS_INLINE bool try_lock() noexcept {
34 // First do a relaxed load to check if lock is free in order to prevent
35 // unnecessary cache misses if someone does while(!try_lock())
36 return !lock_.load(std::memory_order_relaxed)
37 && !lock_.exchange(true, std::memory_order_acquire);
38 }
39
40 UL_ALWAYS_INLINE void unlock() noexcept { lock_.store(false, std::memory_order_release); }
41
42 protected:
43 Lock(const Lock&) = delete;
44 Lock& operator=(const Lock&) = delete;
45
46 void contended_lock() noexcept;
47
48 std::atomic<bool> lock_ = { 0 };
49};
50
51using LockHolder = std::lock_guard<Lock>;
52
53} // namespace ultralight
#define UL_ALWAYS_INLINE
Definition Defines.h:68
Tiny, efficient spinlock that is optimized for short locking periods but will still intelligently yie...
Definition Lock.h:21
constexpr Lock()=default
UL_ALWAYS_INLINE void unlock() noexcept
Definition Lock.h:40
UL_ALWAYS_INLINE void lock() noexcept
Definition Lock.h:25
void contended_lock() noexcept
UL_ALWAYS_INLINE bool try_lock() noexcept
Definition Lock.h:33
Lock(const Lock &)=delete
std::atomic< bool > lock_
Definition Lock.h:48
Lock & operator=(const Lock &)=delete
Definition StringSTL.h:158
Definition App.h:14
std::lock_guard< Lock > LockHolder
Definition Lock.h:51