diff --git a/icu4c/source/acinclude.m4 b/icu4c/source/acinclude.m4 index a75ab2e294ba..5c89cffa4c06 100644 --- a/icu4c/source/acinclude.m4 +++ b/icu4c/source/acinclude.m4 @@ -85,6 +85,7 @@ powerpc*-apple-darwin*) icu_cv_host_frag=mh-darwin-ppc ;; *-dec-osf*) icu_cv_host_frag=mh-alpha-osf ;; *-*-nto*) icu_cv_host_frag=mh-qnx ;; *-ncr-*) icu_cv_host_frag=mh-mpras ;; +*-wasi*) icu_cv_host_frag=mh-wasi ;; *) icu_cv_host_frag=mh-unknown ;; esac ] diff --git a/icu4c/source/common/putilimp.h b/icu4c/source/common/putilimp.h index 6fe02ff8d289..ace48769dd5f 100644 --- a/icu4c/source/common/putilimp.h +++ b/icu4c/source/common/putilimp.h @@ -103,6 +103,8 @@ typedef size_t uintptr_t; #endif #elif U_PLATFORM == U_PF_OS400 /* not defined */ +#elif defined(__wasi__) + /* not defined */ #else # define U_TZSET tzset #endif @@ -128,6 +130,8 @@ typedef size_t uintptr_t; /* not defined */ #elif U_PLATFORM == U_PF_IPHONE /* not defined */ +#elif defined(__wasi__) + /* not defined */ #else # define U_TIMEZONE timezone #endif @@ -141,6 +145,8 @@ typedef size_t uintptr_t; #endif #elif U_PLATFORM == U_PF_OS400 /* not defined */ +#elif defined(__wasi__) + /* not defined */ #else # define U_TZNAME tzname #endif diff --git a/icu4c/source/common/umutex.cpp b/icu4c/source/common/umutex.cpp index 0c053968dcc8..3b961ed8108c 100644 --- a/icu4c/source/common/umutex.cpp +++ b/icu4c/source/common/umutex.cpp @@ -43,6 +43,7 @@ U_NAMESPACE_BEGIN * *************************************************************************************************/ +#if U_HAVE_ATOMICS namespace { std::mutex *initMutex; std::condition_variable *initCondition; @@ -55,7 +56,9 @@ std::once_flag initFlag; std::once_flag *pInitFlag = &initFlag; } // Anonymous namespace +#endif +#if U_HAVE_ATOMICS U_CDECL_BEGIN static UBool U_CALLCONV umtx_cleanup() { initMutex->~mutex(); @@ -75,8 +78,10 @@ static void U_CALLCONV umtx_init() { ucln_common_registerCleanup(UCLN_COMMON_MUTEX, umtx_cleanup); } U_CDECL_END +#endif +#if U_HAVE_ATOMICS std::mutex *UMutex::getMutex() { std::mutex *retPtr = fMutex.load(std::memory_order_acquire); if (retPtr == nullptr) { @@ -93,14 +98,17 @@ std::mutex *UMutex::getMutex() { U_ASSERT(retPtr != nullptr); return retPtr; } +#endif UMutex *UMutex::gListHead = nullptr; void UMutex::cleanup() { UMutex *next = nullptr; for (UMutex *m = gListHead; m != nullptr; m = next) { +#if U_HAVE_ATOMICS (*m->fMutex).~mutex(); m->fMutex = nullptr; +#endif next = m->fListLink; m->fListLink = nullptr; } @@ -110,20 +118,24 @@ void UMutex::cleanup() { U_CAPI void U_EXPORT2 umtx_lock(UMutex *mutex) { +#if U_HAVE_ATOMICS if (mutex == nullptr) { mutex = &globalMutex; } mutex->lock(); +#endif } U_CAPI void U_EXPORT2 umtx_unlock(UMutex* mutex) { +#if U_HAVE_ATOMICS if (mutex == nullptr) { mutex = &globalMutex; } mutex->unlock(); +#endif } @@ -143,18 +155,22 @@ umtx_unlock(UMutex* mutex) // U_COMMON_API UBool U_EXPORT2 umtx_initImplPreInit(UInitOnce &uio) { +#if U_HAVE_ATOMICS std::call_once(*pInitFlag, umtx_init); std::unique_lock lock(*initMutex); +#endif if (umtx_loadAcquire(uio.fState) == 0) { umtx_storeRelease(uio.fState, 1); return true; // Caller will next call the init function. } else { +#if U_HAVE_ATOMICS while (umtx_loadAcquire(uio.fState) == 1) { // Another thread is currently running the initialization. // Wait until it completes. initCondition->wait(lock); } U_ASSERT(uio.fState == 2); +#endif return false; } } @@ -168,11 +184,13 @@ umtx_initImplPreInit(UInitOnce &uio) { U_COMMON_API void U_EXPORT2 umtx_initImplPostInit(UInitOnce &uio) { +#if U_HAVE_ATOMICS { std::unique_lock lock(*initMutex); umtx_storeRelease(uio.fState, 2); } initCondition->notify_all(); +#endif } U_NAMESPACE_END diff --git a/icu4c/source/common/umutex.h b/icu4c/source/common/umutex.h index 1b8332409c6d..57fb5f4d5e7f 100644 --- a/icu4c/source/common/umutex.h +++ b/icu4c/source/common/umutex.h @@ -20,9 +20,6 @@ #ifndef UMUTEX_H #define UMUTEX_H -#include -#include -#include #include #include "unicode/utypes.h" @@ -37,6 +34,12 @@ #error U_USER_ATOMICS and U_USER_MUTEX_H are not supported #endif +#if U_HAVE_ATOMICS + +#include +#include +#include + // Export an explicit template instantiation of std::atomic. // When building DLLs for Windows this is required as it is used as a data member of the exported SharedObject class. // See digitlst.h, pluralaffix.h, datefmt.h, and others for similar examples. @@ -61,6 +64,7 @@ template struct std::atomic; #endif #endif +#endif // U_HAVE_ATOMICS U_NAMESPACE_BEGIN @@ -70,6 +74,8 @@ U_NAMESPACE_BEGIN * ****************************************************************************/ +#if U_HAVE_ATOMICS + typedef std::atomic u_atomic_int32_t; inline int32_t umtx_loadAcquire(u_atomic_int32_t &var) { @@ -88,6 +94,29 @@ inline int32_t umtx_atomic_dec(u_atomic_int32_t *var) { return var->fetch_sub(1) - 1; } +#else + +// No atomic operations available. Use a simple int32_t instead. + +typedef int32_t u_atomic_int32_t; + +inline int32_t umtx_loadAcquire(u_atomic_int32_t &var) { + return var; +} + +inline void umtx_storeRelease(u_atomic_int32_t &var, int32_t val) { + var = val; +} + +inline int32_t umtx_atomic_inc(u_atomic_int32_t *var) { + return ++(*var); +} + +inline int32_t umtx_atomic_dec(u_atomic_int32_t *var) { + return --(*var); +} + +#endif // U_HAVE_ATOMICS /************************************************************************************************* * @@ -227,17 +256,25 @@ class U_COMMON_API UMutex { // requirements for C++ BasicLockable, allows UMutex to work with std::lock_guard void lock() { +#if U_HAVE_ATOMICS std::mutex *m = fMutex.load(std::memory_order_acquire); if (m == nullptr) { m = getMutex(); } m->lock(); +#endif + } + void unlock() { +#if U_HAVE_ATOMICS + fMutex.load(std::memory_order_relaxed)->unlock(); +#endif } - void unlock() { fMutex.load(std::memory_order_relaxed)->unlock(); } static void cleanup(); private: +#if U_HAVE_ATOMICS alignas(std::mutex) char fStorage[sizeof(std::mutex)] {}; std::atomic fMutex { nullptr }; +#endif /** All initialized UMutexes are kept in a linked list, so that they can be found, * and the underlying std::mutex destructed, by u_cleanup(). @@ -249,7 +286,9 @@ class U_COMMON_API UMutex { * Initial fast check is inline, in lock(). The returned value may never * be nullptr. */ +#if U_HAVE_ATOMICS std::mutex *getMutex(); +#endif }; diff --git a/icu4c/source/common/unicode/platform.h b/icu4c/source/common/unicode/platform.h index b8eb52d6ce68..ff36e0db0cb8 100644 --- a/icu4c/source/common/unicode/platform.h +++ b/icu4c/source/common/unicode/platform.h @@ -313,6 +313,20 @@ # define U_PLATFORM_IS_DARWIN_BASED 0 #endif +/** + * \def U_HAVE_ATOMICS + * Defines whether the platform supports atomic operations. + * @internal + */ +#ifdef U_HAVE_ATOMICS + /* Use the predefined value. */ +#elif defined(__wasi__) && !defined(_REENTRANT) + /* WASI does not support atomics when wasi-threads feature is not enabled */ +# define U_HAVE_ATOMICS 0 +#else +# define U_HAVE_ATOMICS 1 +#endif + /*===========================================================================*/ /** @{ Compiler and environment features */ /*===========================================================================*/ diff --git a/icu4c/source/common/unifiedcache.cpp b/icu4c/source/common/unifiedcache.cpp index 68af4e04c1b4..48e20ae5e8f4 100644 --- a/icu4c/source/common/unifiedcache.cpp +++ b/icu4c/source/common/unifiedcache.cpp @@ -13,15 +13,42 @@ #include "unifiedcache.h" #include // For std::max() +#if U_HAVE_ATOMICS #include +#endif #include "uassert.h" #include "uhash.h" #include "ucln_cmn.h" static icu::UnifiedCache *gCache = nullptr; +#if U_HAVE_ATOMICS static std::mutex *gCacheMutex = nullptr; static std::condition_variable *gInProgressValueAddedCond; + +static void initMutex() { + gCacheMutex = STATIC_NEW(std::mutex); + gInProgressValueAddedCond = STATIC_NEW(std::condition_variable); +} + +static void cleanupMutex() { + gCacheMutex->~mutex(); + gCacheMutex = nullptr; + gInProgressValueAddedCond->~condition_variable(); + gInProgressValueAddedCond = nullptr; +} + +#define UNIFIED_CACHE_LOCK_GUARD std::lock_guard lock(*gCacheMutex) + +#else +// No atomics, no mutexes. +static void initMutex() {} +static void cleanupMutex() {} + +#define UNIFIED_CACHE_LOCK_GUARD do {} while (0) + +#endif + static icu::UInitOnce gCacheInitOnce {}; static const int32_t MAX_EVICT_ITERATIONS = 10; @@ -34,10 +61,7 @@ static UBool U_CALLCONV unifiedcache_cleanup() { gCacheInitOnce.reset(); delete gCache; gCache = nullptr; - gCacheMutex->~mutex(); - gCacheMutex = nullptr; - gInProgressValueAddedCond->~condition_variable(); - gInProgressValueAddedCond = nullptr; + cleanupMutex(); return true; } U_CDECL_END @@ -72,8 +96,7 @@ static void U_CALLCONV cacheInit(UErrorCode &status) { ucln_common_registerCleanup( UCLN_COMMON_UNIFIED_CACHE, unifiedcache_cleanup); - gCacheMutex = STATIC_NEW(std::mutex); - gInProgressValueAddedCond = STATIC_NEW(std::condition_variable); + initMutex(); gCache = new UnifiedCache(status); if (gCache == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -135,28 +158,28 @@ void UnifiedCache::setEvictionPolicy( status = U_ILLEGAL_ARGUMENT_ERROR; return; } - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; fMaxUnused = count; fMaxPercentageOfInUse = percentageOfInUseItems; } int32_t UnifiedCache::unusedCount() const { - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; return uhash_count(fHashtable) - fNumValuesInUse; } int64_t UnifiedCache::autoEvictedCount() const { - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; return fAutoEvictedCount; } int32_t UnifiedCache::keyCount() const { - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; return uhash_count(fHashtable); } void UnifiedCache::flush() const { - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; // Use a loop in case cache items that are flushed held hard references to // other cache items making those additional cache items eligible for @@ -165,7 +188,7 @@ void UnifiedCache::flush() const { } void UnifiedCache::handleUnreferencedObject() const { - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; --fNumValuesInUse; _runEvictionSlice(); } @@ -184,7 +207,7 @@ void UnifiedCache::dump() { } void UnifiedCache::dumpContents() const { - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; _dumpContents(); } @@ -224,7 +247,7 @@ UnifiedCache::~UnifiedCache() { // Now all that should be left in the cache are entries that refer to // each other and entries with hard references from outside the cache. // Nothing we can do about these so proceed to wipe out the cache. - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; _flush(true); } uhash_close(fHashtable); @@ -325,7 +348,7 @@ void UnifiedCache::_putIfAbsentAndGet( const CacheKeyBase &key, const SharedObject *&value, UErrorCode &status) const { - std::lock_guard lock(*gCacheMutex); + UNIFIED_CACHE_LOCK_GUARD; const UHashElement *element = uhash_find(fHashtable, &key); if (element != nullptr && !_inProgress(element)) { _fetch(element, value, status); @@ -350,14 +373,18 @@ UBool UnifiedCache::_poll( UErrorCode &status) const { U_ASSERT(value == nullptr); U_ASSERT(status == U_ZERO_ERROR); +#if U_HAVE_ATOMICS std::unique_lock lock(*gCacheMutex); +#endif const UHashElement *element = uhash_find(fHashtable, &key); // If the hash table contains an inProgress placeholder entry for this key, // this means that another thread is currently constructing the value object. // Loop, waiting for that construction to complete. while (element != nullptr && _inProgress(element)) { +#if U_HAVE_ATOMICS gInProgressValueAddedCond->wait(lock); +#endif element = uhash_find(fHashtable, &key); } @@ -428,9 +455,11 @@ void UnifiedCache::_put( U_ASSERT(oldValue == fNoValue); removeSoftRef(oldValue); +#if U_HAVE_ATOMICS // Tell waiting threads that we replace in-progress status with // an error. gInProgressValueAddedCond->notify_all(); +#endif } void UnifiedCache::_fetch( diff --git a/icu4c/source/config/mh-wasi b/icu4c/source/config/mh-wasi new file mode 100644 index 000000000000..a8d776684f2f --- /dev/null +++ b/icu4c/source/config/mh-wasi @@ -0,0 +1,76 @@ +## -*-makefile-*- +## Copyright (C) 2024 and later: Unicode, Inc. and others. +## License & terms of use: http://www.unicode.org/copyright.html +## WASI-specific setup + +## Commands to generate dependency files +GEN_DEPS.c= $(CC) -E -MM $(DEFS) $(CPPFLAGS) +GEN_DEPS.cc= $(CXX) -E -MM $(DEFS) $(CPPFLAGS) $(CXXFLAGS) + +## Flags for position independent code +SHAREDLIBCFLAGS = -fPIC +SHAREDLIBCXXFLAGS = -fPIC +SHAREDLIBCPPFLAGS = -DPIC + +## Additional flags when building libraries and with threads +# WASI Preview 1 without wasi-threads does not support threads +THREADSCPPFLAGS = +LIBCPPFLAGS = + +## Compiler switch to embed a runtime search path +LD_RPATH= +LD_RPATH_PRE = + +## These are the library specific LDFLAGS +LDFLAGSICUDT=-nodefaultlibs -nostdlib + +## Shared object suffix +SO = so +## Non-shared intermediate object suffix +STATIC_O = ao + +## Compilation rules +%.$(STATIC_O): $(srcdir)/%.c + $(call SILENT_COMPILE,$(strip $(COMPILE.c) $(STATICCPPFLAGS) $(STATICCFLAGS)) -o $@ $<) +%.o: $(srcdir)/%.c + $(call SILENT_COMPILE,$(strip $(COMPILE.c) $(DYNAMICCPPFLAGS) $(DYNAMICCFLAGS)) -o $@ $<) + +%.$(STATIC_O): $(srcdir)/%.cpp + $(call SILENT_COMPILE,$(strip $(COMPILE.cc) $(STATICCPPFLAGS) $(STATICCXXFLAGS)) -o $@ $<) +%.o: $(srcdir)/%.cpp + $(call SILENT_COMPILE,$(strip $(COMPILE.cc) $(DYNAMICCPPFLAGS) $(DYNAMICCXXFLAGS)) -o $@ $<) + + +## Dependency rules +%.d: $(srcdir)/%.c + $(call ICU_MSG,(deps)) $< + @$(SHELL) -ec '$(GEN_DEPS.c) $< \ + | sed '\''s%\($*\)\.o[ :]*%\1.o $@ : %g'\'' > $@; \ + [ -s $@ ] || rm -f $@' + +%.d: $(srcdir)/%.cpp + $(call ICU_MSG,(deps)) $< + @$(SHELL) -ec '$(GEN_DEPS.cc) $< \ + | sed '\''s%\($*\)\.o[ :]*%\1.o $@ : %g'\'' > $@; \ + [ -s $@ ] || rm -f $@' + +## Versioned libraries rules + +%.$(SO).$(SO_TARGET_VERSION_MAJOR): %.$(SO).$(SO_TARGET_VERSION) + $(RM) $@ && ln -s ${atomicParser.exchange(nullptr); delete fields->atomicCurrencyParser.exchange(nullptr); +#else + delete fields->atomicParser; + delete fields->atomicCurrencyParser; +#endif delete fields; } @@ -1637,8 +1642,15 @@ void DecimalFormat::touch(UErrorCode& status) { setupFastFormat(); // Delete the parsers if they were made previously +#if U_HAVE_ATOMICS delete fields->atomicParser.exchange(nullptr); delete fields->atomicCurrencyParser.exchange(nullptr); +#else + delete fields->atomicParser; + fields->atomicParser = nullptr; + delete fields->atomicCurrencyParser; + fields->atomicCurrencyParser = nullptr; +#endif // In order for the getters to work, we need to populate some fields in NumberFormat. NumberFormat::setCurrency(fields->exportedProperties.currency.get(status).getISOCurrency(), status); @@ -1673,7 +1685,11 @@ const numparse::impl::NumberParserImpl* DecimalFormat::getParser(UErrorCode& sta } // First try to get the pre-computed parser +#if U_HAVE_ATOMICS auto* ptr = fields->atomicParser.load(); +#else + auto* ptr = fields->atomicParser; +#endif if (ptr != nullptr) { return ptr; } @@ -1692,6 +1708,7 @@ const numparse::impl::NumberParserImpl* DecimalFormat::getParser(UErrorCode& sta // it is set to what is actually stored in the atomic // if another thread beat us to computing the parser object. auto* nonConstThis = const_cast(this); +#if U_HAVE_ATOMICS if (!nonConstThis->fields->atomicParser.compare_exchange_strong(ptr, temp)) { // Another thread beat us to computing the parser delete temp; @@ -1700,13 +1717,21 @@ const numparse::impl::NumberParserImpl* DecimalFormat::getParser(UErrorCode& sta // Our copy of the parser got stored in the atomic return temp; } +#else + nonConstThis->fields->atomicParser = temp; + return temp; +#endif } const numparse::impl::NumberParserImpl* DecimalFormat::getCurrencyParser(UErrorCode& status) const { if (U_FAILURE(status)) { return nullptr; } // First try to get the pre-computed parser +#if U_HAVE_ATOMICS auto* ptr = fields->atomicCurrencyParser.load(); +#else + auto* ptr = fields->atomicCurrencyParser; +#endif if (ptr != nullptr) { return ptr; } @@ -1721,6 +1746,7 @@ const numparse::impl::NumberParserImpl* DecimalFormat::getCurrencyParser(UErrorC // Note: ptr starts as nullptr; during compare_exchange, it is set to what is actually stored in the // atomic if another thread beat us to computing the parser object. auto* nonConstThis = const_cast(this); +#if U_HAVE_ATOMICS if (!nonConstThis->fields->atomicCurrencyParser.compare_exchange_strong(ptr, temp)) { // Another thread beat us to computing the parser delete temp; @@ -1729,6 +1755,10 @@ const numparse::impl::NumberParserImpl* DecimalFormat::getCurrencyParser(UErrorC // Our copy of the parser got stored in the atomic return temp; } +#else + nonConstThis->fields->atomicCurrencyParser = temp; + return temp; +#endif } void diff --git a/icu4c/source/i18n/number_mapper.h b/icu4c/source/i18n/number_mapper.h index fc5617cb4633..afac55415b5c 100644 --- a/icu4c/source/i18n/number_mapper.h +++ b/icu4c/source/i18n/number_mapper.h @@ -7,7 +7,9 @@ #ifndef __NUMBER_MAPPER_H__ #define __NUMBER_MAPPER_H__ -#include +#if U_HAVE_ATOMICS +# include +#endif #include "number_types.h" #include "unicode/currpinf.h" #include "standardplural.h" @@ -196,10 +198,18 @@ struct DecimalFormatFields : public UMemory { LocalizedNumberFormatter formatter; /** The lazy-computed parser for .parse() */ +#if U_HAVE_ATOMICS std::atomic<::icu::numparse::impl::NumberParserImpl*> atomicParser = {}; +#else + ::icu::numparse::impl::NumberParserImpl* atomicParser = {}; +#endif /** The lazy-computed parser for .parseCurrency() */ +#if U_HAVE_ATOMICS std::atomic<::icu::numparse::impl::NumberParserImpl*> atomicCurrencyParser = {}; +#else + ::icu::numparse::impl::NumberParserImpl* atomicCurrencyParser = {}; +#endif /** Small object ownership warehouse for the formatter and parser */ DecimalFormatWarehouse warehouse; diff --git a/icu4c/source/i18n/numrange_fluent.cpp b/icu4c/source/i18n/numrange_fluent.cpp index a02ae5b9c2c1..10ccb0887be1 100644 --- a/icu4c/source/i18n/numrange_fluent.cpp +++ b/icu4c/source/i18n/numrange_fluent.cpp @@ -248,29 +248,51 @@ LocalizedNumberRangeFormatter::LocalizedNumberRangeFormatter(NFS&& src) noe : NFS(std::move(src)) { // Steal the compiled formatter LNF&& _src = static_cast(src); +#if U_HAVE_ATOMICS auto* stolen = _src.fAtomicFormatter.exchange(nullptr); delete fAtomicFormatter.exchange(stolen); +#else + delete fAtomicFormatter; + fAtomicFormatter = _src.fAtomicFormatter; + _src.fAtomicFormatter = nullptr; +#endif } LocalizedNumberRangeFormatter& LocalizedNumberRangeFormatter::operator=(const LNF& other) { if (this == &other) { return *this; } // self-assignment: no-op NFS::operator=(static_cast&>(other)); +#if U_HAVE_ATOMICS // Do not steal; just clear delete fAtomicFormatter.exchange(nullptr); +#else + delete fAtomicFormatter; + fAtomicFormatter = nullptr; +#endif return *this; } LocalizedNumberRangeFormatter& LocalizedNumberRangeFormatter::operator=(LNF&& src) noexcept { NFS::operator=(static_cast&&>(src)); +#if U_HAVE_ATOMICS // Steal the compiled formatter auto* stolen = src.fAtomicFormatter.exchange(nullptr); delete fAtomicFormatter.exchange(stolen); +#else + delete fAtomicFormatter; + fAtomicFormatter = src.fAtomicFormatter; + src.fAtomicFormatter = nullptr; +#endif return *this; } LocalizedNumberRangeFormatter::~LocalizedNumberRangeFormatter() { +#if U_HAVE_ATOMICS delete fAtomicFormatter.exchange(nullptr); +#else + delete fAtomicFormatter; + fAtomicFormatter = nullptr; +#endif } LocalizedNumberRangeFormatter::LocalizedNumberRangeFormatter(const RangeMacroProps& macros, const Locale& locale) { @@ -365,7 +387,11 @@ LocalizedNumberRangeFormatter::getFormatter(UErrorCode& status) const { } // First try to get the pre-computed formatter +#if U_HAVE_ATOMICS auto* ptr = fAtomicFormatter.load(); +#else + auto* ptr = fAtomicFormatter; +#endif if (ptr != nullptr) { return ptr; } @@ -380,6 +406,7 @@ LocalizedNumberRangeFormatter::getFormatter(UErrorCode& status) const { // it is set to what is actually stored in the atomic // if another thread beat us to computing the formatter object. auto* nonConstThis = const_cast(this); +#if U_HAVE_ATOMICS if (!nonConstThis->fAtomicFormatter.compare_exchange_strong(ptr, temp.getAlias())) { // Another thread beat us to computing the formatter return ptr; @@ -387,6 +414,10 @@ LocalizedNumberRangeFormatter::getFormatter(UErrorCode& status) const { // Our copy of the formatter got stored in the atomic return temp.orphan(); } +#else + nonConstThis->fAtomicFormatter = temp.getAlias(); + return temp.orphan(); +#endif } diff --git a/icu4c/source/i18n/unicode/numberrangeformatter.h b/icu4c/source/i18n/unicode/numberrangeformatter.h index b8bbc1ba072d..be3e4708c71c 100644 --- a/icu4c/source/i18n/unicode/numberrangeformatter.h +++ b/icu4c/source/i18n/unicode/numberrangeformatter.h @@ -10,7 +10,9 @@ #if !UCONFIG_NO_FORMATTING +#if U_HAVE_ATOMICS #include +#endif #include "unicode/appendable.h" #include "unicode/fieldpos.h" #include "unicode/formattedvalue.h" @@ -77,7 +79,9 @@ struct UFormattedNumberRangeImpl; } // namespace icu::number U_NAMESPACE_END +#if U_HAVE_ATOMICS template struct U_I18N_API std::atomic< U_NAMESPACE_QUALIFIER number::impl::NumberRangeFormatterImpl*>; +#endif U_NAMESPACE_BEGIN namespace number { // icu::number @@ -579,7 +583,11 @@ class U_I18N_API LocalizedNumberRangeFormatter ~LocalizedNumberRangeFormatter(); private: +#if U_HAVE_ATOMICS std::atomic fAtomicFormatter = {}; +#else + impl::NumberRangeFormatterImpl* fAtomicFormatter = nullptr; +#endif const impl::NumberRangeFormatterImpl* getFormatter(UErrorCode& stauts) const;