C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Lock-free atomic operations that use a different-sized type from the object or subobject

From: John Platts <john_platts_at_[hidden]>
Date: Wed, 31 May 2023 10:49:23 +0000
From: Std-Proposals <std-proposals-bounces_at_[hidden]> on behalf of Thiago Macieira via Std-Proposals <std-proposals_at_[hidden]> Sent: Friday, May 26, 2023 12:32 PM To: std-proposals_at_[hidden] <std-proposals_at_[hidden]> Cc: Thiago Macieira <thiago_at_[hidden]> Subject: Re: [std-proposals] Lock-free atomic operations that use a different-sized type from the object or subobject   On Friday, 26 May 2023 07:01:18 PDT John Platts via Std-Proposals wrote: > Adding lock-free atomic operations that can operate on any valid pointer to > a suitably-aligned type such as lock_free_atomic_load_32, > lock_free_atomic_store_32, lock_free_compare_exchange_weak_32, and > lock_free_compare_exchange_strong_32 addresses issues that are not > addressed by the std::memcpy and std::bit_cast operations. I'm missing something: what's the difference between what you're proposing and what's already in std::atomic and std::atomic_ref? You're saying that "it's equivalent to" the std::atomic_ref example, but you didn't say why you can't just use that. -- Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org    Software Architect - Intel DCAI Cloud Engineering I am well aware that C++20 has the std::atomic_ref class. The issue that I am trying to resolve is to be able to do atomic accesses like the following without having to resort to inline assembly or undefined behavior: struct SomeStruct { alignas(16) char ch_arr[16]; }; void SomeFunctionThatDoesAtomicAccess(SomeStruct* p) { std::atomic_ref<std::uint32_t> u32_atomic_ref_1( *reinterpret_cast<std::uint32_t*>(ch_arr + 4)); std::atomic_ref<std::uint32_t> u32_atomic_ref_2( *reinterpret_cast<std::uint32_t*>(ch_arr + 8)); auto x = u32_atomic_ref_1.load(std::memory_order_acquire); u32_atomic_ref_2.store(x, std::memory_order_relaxed); } The code above has undefined behavior according to the C++ standard (due to the use of the wrong type), and the use of std::memcpy does not have the atomicity guarantees that would be needed for memory that is concurrently accessed by 2 or more threads.

Received on 2023-05-31 10:49:27