| 1 | // Copyright (C) 2020-2025 Free Software Foundation, Inc. |
| 2 | // |
| 3 | // This file is part of the GNU ISO C++ Library. This library is free |
| 4 | // software; you can redistribute it and/or modify it under the |
| 5 | // terms of the GNU General Public License as published by the |
| 6 | // Free Software Foundation; either version 3, or (at your option) |
| 7 | // any later version. |
| 8 | |
| 9 | // This library is distributed in the hope that it will be useful, |
| 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | // GNU General Public License for more details. |
| 13 | |
| 14 | // You should have received a copy of the GNU General Public License along |
| 15 | // with this library; see the file COPYING3. If not see |
| 16 | // <http://www.gnu.org/licenses/>. |
| 17 | |
| 18 | // { dg-add-options libatomic } |
| 19 | // { dg-do run { target c++20 } } |
| 20 | // { dg-additional-options "-pthread" { target pthread } } |
| 21 | // { dg-require-gthreads "" } |
| 22 | |
| 23 | #include <stop_token> |
| 24 | #include <atomic> |
| 25 | #include <thread> |
| 26 | #include <testsuite_hooks.h> |
| 27 | |
| 28 | struct F |
| 29 | { |
| 30 | static std::atomic<int> stage; |
| 31 | |
| 32 | F(int) { } |
| 33 | |
| 34 | ~F() |
| 35 | { |
| 36 | // PR libstdc++/92895 |
| 37 | // Callback function must not be destroyed while still executing. |
| 38 | VERIFY( stage == 4 ); |
| 39 | } |
| 40 | |
| 41 | void operator()() const noexcept |
| 42 | { |
| 43 | stage = 2; // trigger destructor of stop_callback that owns *this |
| 44 | while (stage == 2) |
| 45 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 46 | std::this_thread::sleep_for(std::chrono::milliseconds(500)); |
| 47 | stage = 4; // destructor checks for this |
| 48 | } |
| 49 | }; |
| 50 | |
| 51 | std::atomic<int> F::stage{0}; |
| 52 | |
| 53 | void |
| 54 | test01() |
| 55 | { |
| 56 | std::stop_source ssrc; |
| 57 | std::stop_token stok = ssrc.get_token(); |
| 58 | std::thread t1([&ssrc] { |
| 59 | while (F::stage == 0) |
| 60 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 61 | ssrc.request_stop(); |
| 62 | while (F::stage != 5) |
| 63 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 64 | }); |
| 65 | |
| 66 | std::thread t2([&ssrc] { |
| 67 | std::stop_callback<F> cb(ssrc.get_token(), 0); |
| 68 | F::stage = 1; // trigger stop request in other thread, which runs callback |
| 69 | while (F::stage == 1) |
| 70 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 71 | F::stage = 3; |
| 72 | // stop_callback destructor should block until callback completes |
| 73 | }); |
| 74 | |
| 75 | t2.join(); |
| 76 | F::stage = 5; // allow first thread to exit |
| 77 | t1.join(); |
| 78 | } |
| 79 | |
| 80 | int main() |
| 81 | { |
| 82 | test01(); |
| 83 | } |