| 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-exception |
| 5 | // |
| 6 | //===----------------------------------------------------------------------===// |
| 7 | |
| 8 | // UNSUPPORTED: c++03, c++11, c++14, c++17 |
| 9 | // UNSUPPORTED: no-threads |
| 10 | // XFAIL: availability-synchronization_library-missing |
| 11 | // XFAIL: !has-64-bit-atomics |
| 12 | // XFAIL: !has-1024-bit-atomics |
| 13 | |
| 14 | // void notify_all() const noexcept; |
| 15 | |
| 16 | #include <atomic> |
| 17 | #include <cassert> |
| 18 | #include <thread> |
| 19 | #include <type_traits> |
| 20 | #include <vector> |
| 21 | |
| 22 | #include "atomic_helpers.h" |
| 23 | #include "make_test_thread.h" |
| 24 | #include "test_macros.h" |
| 25 | |
| 26 | template <typename T> |
| 27 | struct TestNotifyAll { |
| 28 | void operator()() const { |
| 29 | T x(T(1)); |
| 30 | std::atomic_ref<T> const a(x); |
| 31 | |
| 32 | bool done = false; |
| 33 | std::atomic<int> started_num = 0; |
| 34 | std::atomic<int> wait_done_num = 0; |
| 35 | |
| 36 | constexpr auto number_of_threads = 8; |
| 37 | std::vector<std::thread> threads; |
| 38 | threads.reserve(n: number_of_threads); |
| 39 | |
| 40 | for (auto j = 0; j < number_of_threads; ++j) { |
| 41 | threads.push_back(support::make_test_thread([&a, &started_num, &done, &wait_done_num] { |
| 42 | started_num.fetch_add(1, std::memory_order::relaxed); |
| 43 | |
| 44 | a.wait(T(1)); |
| 45 | wait_done_num.fetch_add(1, std::memory_order::relaxed); |
| 46 | |
| 47 | // likely to fail if wait did not block |
| 48 | assert(done); |
| 49 | })); |
| 50 | } |
| 51 | |
| 52 | while (started_num.load(std::memory_order::relaxed) != number_of_threads) { |
| 53 | std::this_thread::yield(); |
| 54 | } |
| 55 | |
| 56 | std::this_thread::sleep_for(rtime: std::chrono::milliseconds(1)); |
| 57 | |
| 58 | done = true; |
| 59 | a.store(T(3)); |
| 60 | a.notify_all(); |
| 61 | |
| 62 | // notify_all should unblock all the threads so that the loop below won't stuck |
| 63 | while (wait_done_num.load(std::memory_order::relaxed) != number_of_threads) { |
| 64 | std::this_thread::yield(); |
| 65 | } |
| 66 | |
| 67 | for (auto& thread : threads) { |
| 68 | thread.join(); |
| 69 | } |
| 70 | |
| 71 | ASSERT_NOEXCEPT(a.notify_all()); |
| 72 | } |
| 73 | }; |
| 74 | |
| 75 | int main(int, char**) { |
| 76 | TestEachAtomicType<TestNotifyAll>()(); |
| 77 | return 0; |
| 78 | } |
| 79 | |