|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | +// See https://llvm.org/LICENSE.txt for license information. |
| 5 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | +// |
| 7 | +//===----------------------------------------------------------------------===// |
| 8 | + |
| 9 | +// UNSUPPORTED: no-threads |
| 10 | +// UNSUPPORTED: c++03, c++11, c++14, c++17 |
| 11 | + |
| 12 | +// This is a stress test for std::atomic::wait for lost wake ups. |
| 13 | + |
| 14 | +// <atomic> |
| 15 | + |
| 16 | +#include <atomic> |
| 17 | +#include <functional> |
| 18 | +#include <thread> |
| 19 | +#include <vector> |
| 20 | + |
| 21 | +#include "make_test_thread.h" |
| 22 | + |
| 23 | +constexpr int num_waiters = 8; |
| 24 | +constexpr int num_iterations = 10'000; |
| 25 | + |
| 26 | +int main(int, char**) { |
| 27 | + for (int run = 0; run < 20; ++run) { |
| 28 | + std::atomic<int> waiter_ready(0); |
| 29 | + std::atomic<int> state(0); |
| 30 | + |
| 31 | + auto wait = [&]() { |
| 32 | + for (int i = 0; i < num_iterations; ++i) { |
| 33 | + auto old_state = state.load(std::memory_order_acquire); |
| 34 | + waiter_ready.fetch_add(1, std::memory_order_acq_rel); |
| 35 | + state.wait(old_state, std::memory_order_acquire); |
| 36 | + } |
| 37 | + }; |
| 38 | + |
| 39 | + auto notify = [&] { |
| 40 | + for (int i = 0; i < num_iterations; ++i) { |
| 41 | + while (waiter_ready.load(std::memory_order_acquire) < num_waiters) { |
| 42 | + std::this_thread::yield(); |
| 43 | + } |
| 44 | + waiter_ready.store(0, std::memory_order_release); |
| 45 | + state.fetch_add(1, std::memory_order_acq_rel); |
| 46 | + state.notify_all(); |
| 47 | + } |
| 48 | + }; |
| 49 | + |
| 50 | + std::vector<std::jthread> threads; |
| 51 | + for (int i = 0; i < num_waiters; ++i) |
| 52 | + threads.push_back(support::make_test_jthread(wait)); |
| 53 | + |
| 54 | + threads.push_back(support::make_test_jthread(notify)); |
| 55 | + } |
| 56 | + |
| 57 | + return 0; |
| 58 | +} |
0 commit comments