[libcxx-commits] [libcxx] [libc++] Implement C++20 atomic_ref (PR #76647)
Louis Dionne via libcxx-commits
libcxx-commits at lists.llvm.org
Mon Mar 11 11:06:10 PDT 2024
================
@@ -0,0 +1,91 @@
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17
+
+// bool compare_exchange_weak(T&, T, memory_order, memory_order) const noexcept;
+// bool compare_exchange_weak(T&, T, memory_order = memory_order::seq_cst) const noexcept;
+
+#include <atomic>
+#include <concepts>
+#include <cassert>
+#include <type_traits>
+
+#include "test_macros.h"
+
+template <typename T>
+void test_compare_exchange_weak() {
+ {
+ T x(T(1));
+ std::atomic_ref<T> const a(x);
+
+ T t(T(1));
+ std::same_as<bool> auto y = a.compare_exchange_weak(t, T(2));
+ assert(y == true);
+ assert(a == T(2));
+ assert(t == T(1));
+ y = a.compare_exchange_weak(t, T(3));
+ assert(y == false);
+ assert(a == T(2));
+ assert(t == T(2));
+
+ ASSERT_NOEXCEPT(a.compare_exchange_weak(t, T(2)));
+ }
+ {
+ T x(T(1));
+ std::atomic_ref<T> const a(x);
+
+ T t(T(1));
+ std::same_as<bool> auto y = a.compare_exchange_weak(t, T(2), std::memory_order_seq_cst);
+ assert(y == true);
+ assert(a == T(2));
+ assert(t == T(1));
+ y = a.compare_exchange_weak(t, T(3), std::memory_order_seq_cst);
+ assert(y == false);
+ assert(a == T(2));
+ assert(t == T(2));
+
+ ASSERT_NOEXCEPT(a.compare_exchange_weak(t, T(2), std::memory_order_seq_cst));
+ }
+ {
+ T x(T(1));
+ std::atomic_ref<T> const a(x);
+
+ T t(T(1));
+ std::same_as<bool> auto y = a.compare_exchange_weak(t, T(2), std::memory_order_release, std::memory_order_relaxed);
+ assert(y == true);
+ assert(a == T(2));
+ assert(t == T(1));
+ y = a.compare_exchange_weak(t, T(3), std::memory_order_release, std::memory_order_relaxed);
+ assert(y == false);
+ assert(a == T(2));
+ assert(t == T(2));
+
+ ASSERT_NOEXCEPT(a.compare_exchange_weak(t, T(2), std::memory_order_release, std::memory_order_relaxed));
+ }
+}
+
+void test() {
+ test_compare_exchange_weak<int>();
+
+ test_compare_exchange_weak<float>();
+
+ test_compare_exchange_weak<int*>();
+
+ struct X {
+ int i;
+ //X() = default;
+ X(int ii) noexcept : i(ii) {}
+ bool operator==(X o) const { return i == o.i; }
+ };
+ test_compare_exchange_weak<X>();
----------------
ldionne wrote:
You could use `libcxx/test/support/type_algorithms.h` or `libcxx/test/support/atomic_helpers.h` for instantiating on multiple types.
https://github.com/llvm/llvm-project/pull/76647
More information about the libcxx-commits
mailing list