ladybird/Libraries/LibSync/Once.h
R-Goc 02bb892d7a LibThreading/LibSync: Split out sync primitives
This commit splits out synchronization primitives from LibThreading into
LibSync. This is because LibThreading depends on LibCore, while LibCore
needs the synchronization primitives from LibThreading. This worked
while they were header only, but when I tried to add an implementation
file it ran into the circular dependency. To abstract away the pthread
implementation using cpp files is necessary so the synchronization
primitives were moved to a separate library.
2026-05-08 18:58:35 -05:00

36 lines
879 B
C++

/*
* Copyright (c) 2025, Ryszard Goc <ryszardgoc@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Atomic.h>
#include <AK/Concepts.h>
#include <LibSync/Mutex.h>
namespace Sync {
struct OnceFlag {
Sync::Mutex mutex;
Atomic<bool> has_been_called { false };
};
template<VoidFunction Callable>
void call_once(OnceFlag& flag, Callable&& callable)
{
if (!flag.has_been_called.load(MemoryOrder::memory_order_acquire)) {
Sync::MutexLocker lock(flag.mutex);
// Another thread may have called the function while we were waiting on the mutex
// The mutex guarantees exclusivity so we can use relaxed ordering
if (flag.has_been_called.load(MemoryOrder::memory_order_relaxed))
return;
callable();
flag.has_been_called.store(true, MemoryOrder::memory_order_release);
}
}
}