Path: blob/main/contrib/llvm-project/libcxx/src/call_once.cpp
35154 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include <__mutex/once_flag.h>9#include <__utility/exception_guard.h>1011#ifndef _LIBCPP_HAS_NO_THREADS12# include <__thread/support.h>13#endif1415#include "include/atomic_support.h"1617_LIBCPP_BEGIN_NAMESPACE_STD1819// If dispatch_once_f ever handles C++ exceptions, and if one can get to it20// without illegal macros (unexpected macros not beginning with _UpperCase or21// __lowercase), and if it stops spinning waiting threads, then call_once should22// call into dispatch_once_f instead of here. Relevant radar this code needs to23// keep in sync with: 7741191.2425#ifndef _LIBCPP_HAS_NO_THREADS26static constinit __libcpp_mutex_t mut = _LIBCPP_MUTEX_INITIALIZER;27static constinit __libcpp_condvar_t cv = _LIBCPP_CONDVAR_INITIALIZER;28#endif2930void __call_once(volatile once_flag::_State_type& flag, void* arg, void (*func)(void*)) {31#if defined(_LIBCPP_HAS_NO_THREADS)3233if (flag == once_flag::_Unset) {34auto guard = std::__make_exception_guard([&flag] { flag = once_flag::_Unset; });35flag = once_flag::_Pending;36func(arg);37flag = once_flag::_Complete;38guard.__complete();39}4041#else // !_LIBCPP_HAS_NO_THREADS4243__libcpp_mutex_lock(&mut);44while (flag == once_flag::_Pending)45__libcpp_condvar_wait(&cv, &mut);46if (flag == once_flag::_Unset) {47auto guard = std::__make_exception_guard([&flag] {48__libcpp_mutex_lock(&mut);49__libcpp_relaxed_store(&flag, once_flag::_Unset);50__libcpp_mutex_unlock(&mut);51__libcpp_condvar_broadcast(&cv);52});5354__libcpp_relaxed_store(&flag, once_flag::_Pending);55__libcpp_mutex_unlock(&mut);56func(arg);57__libcpp_mutex_lock(&mut);58__libcpp_atomic_store(&flag, once_flag::_Complete, _AO_Release);59__libcpp_mutex_unlock(&mut);60__libcpp_condvar_broadcast(&cv);61guard.__complete();62} else {63__libcpp_mutex_unlock(&mut);64}6566#endif // !_LIBCPP_HAS_NO_THREADS67}6869_LIBCPP_END_NAMESPACE_STD707172