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// <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://llvm.org/PR23293
24
25#include <future>
26#include <chrono>
27#include <thread>
28#include <memory>
29#include <cassert>
30
31#include "test_macros.h"
32
33int f_async() {
34 typedef std::chrono::milliseconds ms;
35 std::this_thread::sleep_for(ms(200));
36 return 42;
37}
38
39bool ran = false;
40
41int f_deferred() {
42 ran = true;
43 return 42;
44}
45
46void test_each() {
47 {
48 std::future<int> f = std::async(fn&: f_async);
49 int const result = f.get();
50 assert(result == 42);
51 }
52 {
53 std::future<int> f = std::async(policy: std::launch::async, fn&: f_async);
54 int const result = f.get();
55 assert(result == 42);
56 }
57 {
58 ran = false;
59 std::future<int> f = std::async(policy: std::launch::deferred, fn&: f_deferred);
60 assert(ran == false);
61 int const result = f.get();
62 assert(ran == true);
63 assert(result == 42);
64 }
65}
66
67int main(int, char**) {
68 for (int i=0; i < 25; ++i) test_each();
69
70 return 0;
71}
72

source code of libcxx/test/std/thread/futures/futures.async/async_race.pass.cpp