docs
Docs
C++ API
C API
Search API
Ctrl K
1.4
2.0
latest
1.4
Ultralight C++ API
1.4.0
Toggle main menu visibility
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
9
#include <
Ultralight/Defines.h
>
10
#include <atomic>
11
#include <mutex>
// for std::lock_guard<>
12
13
namespace
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
///
21
class
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
30
contended_lock
();
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
51
using
LockHolder
= std::lock_guard<Lock>;
52
53
}
// namespace ultralight
Defines.h
UL_ALWAYS_INLINE
#define UL_ALWAYS_INLINE
Definition
Defines.h:68
ultralight::Lock::Lock
constexpr Lock()=default
ultralight::Lock::unlock
UL_ALWAYS_INLINE void unlock() noexcept
Definition
Lock.h:40
ultralight::Lock::lock
UL_ALWAYS_INLINE void lock() noexcept
Definition
Lock.h:25
ultralight::Lock::contended_lock
void contended_lock() noexcept
ultralight::Lock::try_lock
UL_ALWAYS_INLINE bool try_lock() noexcept
Definition
Lock.h:33
ultralight::Lock::Lock
Lock(const Lock &)=delete
ultralight::Lock::lock_
std::atomic< bool > lock_
Definition
Lock.h:48
ultralight::Lock::operator=
Lock & operator=(const Lock &)=delete
std
Definition
StringSTL.h:158
ultralight
Definition
Bitmap.h:14
ultralight::LockHolder
std::lock_guard< Lock > LockHolder
Definition
Lock.h:51
Ultralight
Lock.h
Docs
C++ API
C API
Version
1.4
2.0
latest
1.4