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: libcpp-has-no-threads
10 // UNSUPPORTED: c++98, c++03
11 
12 // <future>
13 
14 // class packaged_task<R(ArgTypes...)>
15 
16 // void operator()(ArgTypes... args);
17 
18 #include <future>
19 #include <cassert>
20 
21 #include "test_macros.h"
22 
23 class A
24 {
25     long data_;
26 
27 public:
28     explicit A(long i) : data_(i) {}
29 
30     long operator()(long i, long j) const
31     {
32         if (j == 'z')
33             TEST_THROW(A(6));
34         return data_ + i + j;
35     }
36 };
37 
38 void func0(std::packaged_task<double(int, char)> p)
39 {
40     std::this_thread::sleep_for(std::chrono::milliseconds(500));
41     p(3, 'a');
42 }
43 
44 void func1(std::packaged_task<double(int, char)> p)
45 {
46     std::this_thread::sleep_for(std::chrono::milliseconds(500));
47     p(3, 'z');
48 }
49 
50 void func2(std::packaged_task<double(int, char)> p)
51 {
52 #ifndef TEST_HAS_NO_EXCEPTIONS
53     p(3, 'a');
54     try
55     {
56         p(3, 'c');
57     }
58     catch (const std::future_error& e)
59     {
60         assert(e.code() == make_error_code(std::future_errc::promise_already_satisfied));
61     }
62 #else
63     ((void)p);
64 #endif
65 }
66 
67 void func3(std::packaged_task<double(int, char)> p)
68 {
69 #ifndef TEST_HAS_NO_EXCEPTIONS
70     try
71     {
72         p(3, 'a');
73     }
74     catch (const std::future_error& e)
75     {
76         assert(e.code() == make_error_code(std::future_errc::no_state));
77     }
78 #else
79     ((void)p);
80 #endif
81 }
82 
83 int main(int, char**)
84 {
85     {
86         std::packaged_task<double(int, char)> p(A(5));
87         std::future<double> f = p.get_future();
88         std::thread(func0, std::move(p)).detach();
89         assert(f.get() == 105.0);
90     }
91 #ifndef TEST_HAS_NO_EXCEPTIONS
92     {
93         std::packaged_task<double(int, char)> p(A(5));
94         std::future<double> f = p.get_future();
95         std::thread(func1, std::move(p)).detach();
96         try
97         {
98             f.get();
99             assert(false);
100         }
101         catch (const A& e)
102         {
103             assert(e(3, 'a') == 106);
104         }
105     }
106     {
107         std::packaged_task<double(int, char)> p(A(5));
108         std::future<double> f = p.get_future();
109         std::thread t(func2, std::move(p));
110         assert(f.get() == 105.0);
111         t.join();
112     }
113     {
114         std::packaged_task<double(int, char)> p;
115         std::thread t(func3, std::move(p));
116         t.join();
117     }
118 #endif
119 
120   return 0;
121 }
122