| 1 |
// { dg-do run } |
| 2 |
// { dg-additional-options "-pthread" { target pthread } } |
| 3 |
// { dg-require-effective-target c++11 } |
| 4 |
// { dg-require-gthreads "" } |
| 5 |
|
| 6 |
// Copyright (C) 2014-2025 Free Software Foundation, Inc. |
| 7 |
// |
| 8 |
// This file is part of the GNU ISO C++ Library. This library is free |
| 9 |
// software; you can redistribute it and/or modify it under the |
| 10 |
// terms of the GNU General Public License as published by the |
| 11 |
// Free Software Foundation; either version 3, or (at your option) |
| 12 |
// any later version. |
| 13 |
|
| 14 |
// This library is distributed in the hope that it will be useful, |
| 15 |
// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 |
// GNU General Public License for more details. |
| 18 |
|
| 19 |
// You should have received a copy of the GNU General Public License along |
| 20 |
// with this library; see the file COPYING3. If not see |
| 21 |
// <http://www.gnu.org/licenses/>. |
| 22 |
|
| 23 |
// libstdc++/60966 |
| 24 |
// This test hangs if std::promise::~promise() destroys the |
| 25 |
// shared state before std::promise::set_value() finishes using it. |
| 26 |
|
| 27 |
#include <future> |
| 28 |
#include <thread> |
| 29 |
#include <vector> |
| 30 |
|
| 31 |
const int THREADS = 10; |
| 32 |
|
| 33 |
void run_task(std::promise<void>* pr) |
| 34 |
{ |
| 35 |
std::this_thread::sleep_for(std::chrono::milliseconds(100)); |
| 36 |
pr->set_value(); |
| 37 |
} |
| 38 |
|
| 39 |
int main() |
| 40 |
{ |
| 41 |
std::vector<std::promise<void>*> tasks(THREADS); |
| 42 |
std::vector<std::thread> threads(THREADS); |
| 43 |
std::vector<std::future<void>> futures(THREADS); |
| 44 |
|
| 45 |
for (int i = 0; i < THREADS; ++i) |
| 46 |
{ |
| 47 |
std::promise<void>* task = new std::promise<void>; |
| 48 |
tasks[i] = task; |
| 49 |
futures[i] = task->get_future(); |
| 50 |
threads[i] = std::thread(run_task, task); |
| 51 |
} |
| 52 |
|
| 53 |
for (int i = 0; i < THREADS; ++i) |
| 54 |
{ |
| 55 |
// the temporary future releases the state as soon as wait() returns |
| 56 |
std::future<void>(std::move(futures[i])).wait(); |
| 57 |
// state is ready, should now be safe to delete promise, so it |
| 58 |
// releases the shared state too |
| 59 |
delete tasks[i]; |
| 60 |
} |
| 61 |
|
| 62 |
for (auto& t : threads) |
| 63 |
t.join(); |
| 64 |
} |