xref: /llvm-project/libcxx/test/std/thread/futures/futures.unique_future/wait_for.pass.cpp (revision a7f9895cc18995549c7facb96e72718da282a864)
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
11 
12 // ALLOW_RETRIES: 3
13 
14 // <future>
15 
16 // class future<R>
17 
18 // template <class Rep, class Period>
19 //   future_status
20 //   wait_for(const chrono::duration<Rep, Period>& rel_time) const;
21 
22 #include <cassert>
23 #include <chrono>
24 #include <future>
25 
26 #include "make_test_thread.h"
27 #include "test_macros.h"
28 
29 typedef std::chrono::milliseconds ms;
30 
31 static const ms sleepTime(500);
32 static const ms waitTime(5000);
33 
func1(std::promise<int> p)34 void func1(std::promise<int> p)
35 {
36   std::this_thread::sleep_for(sleepTime);
37   p.set_value(3);
38 }
39 
40 int j = 0;
41 
func3(std::promise<int &> p)42 void func3(std::promise<int&> p)
43 {
44   std::this_thread::sleep_for(sleepTime);
45   j = 5;
46   p.set_value(j);
47 }
48 
func5(std::promise<void> p)49 void func5(std::promise<void> p)
50 {
51   std::this_thread::sleep_for(sleepTime);
52   p.set_value();
53 }
54 
55 template <typename T, typename F>
test(F func,bool waitFirst)56 void test(F func, bool waitFirst) {
57   typedef std::chrono::high_resolution_clock Clock;
58   std::promise<T> p;
59   std::future<T> f = p.get_future();
60   Clock::time_point t1, t0 = Clock::now();
61   support::make_test_thread(func, std::move(p)).detach();
62   assert(f.valid());
63   assert(f.wait_for(ms(1)) == std::future_status::timeout);
64   assert(f.valid());
65   if (waitFirst) {
66     f.wait();
67     assert(f.valid());
68     t1 = Clock::now();
69     assert(f.wait_for(ms(waitTime)) == std::future_status::ready);
70     assert(f.valid());
71   } else {
72     assert(f.wait_for(ms(waitTime)) == std::future_status::ready);
73     assert(f.valid());
74     t1 = Clock::now();
75     f.wait();
76     assert(f.valid());
77   }
78   assert(t1 - t0 >= sleepTime);
79 }
80 
main(int,char **)81 int main(int, char**)
82 {
83   test<int>(func1, true);
84   test<int&>(func3, true);
85   test<void>(func5, true);
86   test<int>(func1, false);
87   test<int&>(func3, false);
88   test<void>(func5, false);
89   return 0;
90 }
91