| 1 | // { dg-do run { target c++20 } } |
| 2 | // { dg-require-effective-target gthreads } |
| 3 | // { dg-additional-options "-pthread" { target pthread } } |
| 4 | // { dg-add-options libatomic } |
| 5 | |
| 6 | #include <memory> |
| 7 | #include <thread> |
| 8 | #include <testsuite_hooks.h> |
| 9 | |
| 10 | // Check constexpr constructor. |
| 11 | constinit std::atomic<std::weak_ptr<int>> a; |
| 12 | |
| 13 | void |
| 14 | test_is_lock_free() |
| 15 | { |
| 16 | using test_type = std::atomic<std::weak_ptr<int>>; |
| 17 | static_assert( test_type::is_always_lock_free == false ); |
| 18 | |
| 19 | test_type p; |
| 20 | VERIFY( p.is_lock_free() == false ); |
| 21 | } |
| 22 | |
| 23 | void |
| 24 | test_atomic_weak_ptr() |
| 25 | { |
| 26 | struct A { int a; int b; }; |
| 27 | |
| 28 | auto a = std::make_shared<A>( 0, 42 ); |
| 29 | using ptr_t = std::weak_ptr<A>; |
| 30 | ptr_t wa{ a }; |
| 31 | { |
| 32 | std::atomic<ptr_t> p{ }; |
| 33 | VERIFY( p.load().lock().get() == nullptr ); |
| 34 | } |
| 35 | |
| 36 | std::atomic<ptr_t> p{ wa }; |
| 37 | VERIFY( p.load().lock().get() == a.get() ); |
| 38 | |
| 39 | auto b = std::make_shared<A>( 42, 0 ); |
| 40 | ptr_t wb{ b }; |
| 41 | p.store(wb); |
| 42 | VERIFY( p.load().lock().get() != a.get() ); |
| 43 | VERIFY( p.load().lock().get() == b.get() ); |
| 44 | p.exchange(wa); |
| 45 | VERIFY( p.load().lock().get() != b.get() ); |
| 46 | VERIFY( p.load().lock().get() == a.get() ); |
| 47 | |
| 48 | { |
| 49 | ptr_t aa{ a }; |
| 50 | VERIFY( p.compare_exchange_strong(aa, b, |
| 51 | std::memory_order_seq_cst, |
| 52 | std::memory_order_seq_cst) == true ); |
| 53 | ptr_t bb{ a }; |
| 54 | VERIFY( p.compare_exchange_strong(bb, b, |
| 55 | std::memory_order_seq_cst, |
| 56 | std::memory_order_seq_cst) == false ); |
| 57 | VERIFY( bb.lock().get() == b.get() ); |
| 58 | } |
| 59 | |
| 60 | { |
| 61 | ptr_t bb{ b }; |
| 62 | VERIFY( p.compare_exchange_weak(bb, a, |
| 63 | std::memory_order_seq_cst, |
| 64 | std::memory_order_seq_cst) == true ); |
| 65 | ptr_t aa{ b }; |
| 66 | VERIFY( p.compare_exchange_weak(aa, a, |
| 67 | std::memory_order_seq_cst, |
| 68 | std::memory_order_seq_cst) == false ); |
| 69 | VERIFY( aa.lock().get() == a.get() ); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | void |
| 74 | test_wait_notify() |
| 75 | { |
| 76 | std::atomic<std::weak_ptr<int>> p; |
| 77 | std::weak_ptr<int> a = std::make_shared<int>(); |
| 78 | std::weak_ptr<int> b = std::make_shared<int>(); |
| 79 | |
| 80 | p.store(a); |
| 81 | p.wait(b); |
| 82 | std::thread t([&] |
| 83 | { |
| 84 | p.store(b); |
| 85 | p.notify_one(); |
| 86 | }); |
| 87 | p.wait(a); |
| 88 | t.join(); |
| 89 | } |
| 90 | |
| 91 | int |
| 92 | main() |
| 93 | { |
| 94 | test_is_lock_free(); |
| 95 | test_atomic_weak_ptr(); |
| 96 | test_wait_notify(); |
| 97 | } |