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