Path: blob/main/system/lib/libcxx/src/call_once.cpp
6175 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 <__config>9#include <__mutex/once_flag.h>10#include <__utility/exception_guard.h>1112#if _LIBCPP_HAS_THREADS13# include <__thread/support.h>14#endif1516#include "include/atomic_support.h"1718_LIBCPP_BEGIN_NAMESPACE_STD1920// If dispatch_once_f ever handles C++ exceptions, and if one can get to it21// without illegal macros (unexpected macros not beginning with _UpperCase or22// __lowercase), and if it stops spinning waiting threads, then call_once should23// call into dispatch_once_f instead of here. Relevant radar this code needs to24// keep in sync with: 7741191.2526#if _LIBCPP_HAS_THREADS27static constinit __libcpp_mutex_t mut = _LIBCPP_MUTEX_INITIALIZER;28static constinit __libcpp_condvar_t cv = _LIBCPP_CONDVAR_INITIALIZER;29#endif3031void __call_once(volatile once_flag::_State_type& flag, void* arg, void (*func)(void*)) {32#if !_LIBCPP_HAS_THREADS3334if (flag == once_flag::_Unset) {35auto guard = std::__make_exception_guard([&flag] { flag = once_flag::_Unset; });36flag = once_flag::_Pending;37func(arg);38flag = once_flag::_Complete;39guard.__complete();40}4142#else // !_LIBCPP_HAS_THREADS4344__libcpp_mutex_lock(&mut);45while (flag == once_flag::_Pending)46__libcpp_condvar_wait(&cv, &mut);47if (flag == once_flag::_Unset) {48auto guard = std::__make_exception_guard([&flag] {49__libcpp_mutex_lock(&mut);50__libcpp_relaxed_store(&flag, once_flag::_Unset);51__libcpp_mutex_unlock(&mut);52__libcpp_condvar_broadcast(&cv);53});5455__libcpp_relaxed_store(&flag, once_flag::_Pending);56__libcpp_mutex_unlock(&mut);57func(arg);58__libcpp_mutex_lock(&mut);59__libcpp_atomic_store(&flag, once_flag::_Complete, _AO_Release);60__libcpp_mutex_unlock(&mut);61__libcpp_condvar_broadcast(&cv);62guard.__complete();63} else {64__libcpp_mutex_unlock(&mut);65}6667#endif // !_LIBCPP_HAS_THREADS68}6970_LIBCPP_END_NAMESPACE_STD717273