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 // template <class F, class... Args>
15 //     future<typename result_of<F(Args...)>::type>
16 //     async(F&& f, Args&&... args);
17 
18 // template <class F, class... Args>
19 //     future<typename result_of<F(Args...)>::type>
20 //     async(launch policy, F&& f, Args&&... args);
21 
22 // This test is designed to cause and allow TSAN to detect the race condition
23 // reported in PR23293: https://bugs.llvm.org/show_bug.cgi?id=23293
24 
25 #include <future>
26 #include <chrono>
27 #include <thread>
28 #include <memory>
29 #include <cassert>
30 
31 int f_async() {
32     typedef std::chrono::milliseconds ms;
33     std::this_thread::sleep_for(ms(200));
34     return 42;
35 }
36 
37 bool ran = false;
38 
39 int f_deferred() {
40     ran = true;
41     return 42;
42 }
43 
44 void test_each() {
45     {
46         std::future<int> f = std::async(f_async);
47         int const result = f.get();
48         assert(result == 42);
49     }
50     {
51         std::future<int> f = std::async(std::launch::async, f_async);
52         int const result = f.get();
53         assert(result == 42);
54     }
55     {
56         ran = false;
57         std::future<int> f = std::async(std::launch::deferred, f_deferred);
58         assert(ran == false);
59         int const result = f.get();
60         assert(ran == true);
61         assert(result == 42);
62     }
63 }
64 
65 int main(int, char**) {
66     for (int i=0; i < 25; ++i) test_each();
67 
68   return 0;
69 }
70