1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // <future> 11 12 // class packaged_task<R(ArgTypes...)> 13 14 // void operator()(ArgTypes... args); 15 16 #include <future> 17 #include <cassert> 18 19 class A 20 { 21 long data_; 22 23 public: 24 explicit A(long i) : data_(i) {} 25 26 long operator()(long i, long j) const 27 { 28 if (j == 'z') 29 throw A(6); 30 return data_ + i + j; 31 } 32 }; 33 34 void func0(std::packaged_task<double(int, char)> p) 35 { 36 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 37 p(3, 'a'); 38 } 39 40 void func1(std::packaged_task<double(int, char)> p) 41 { 42 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 43 p(3, 'z'); 44 } 45 46 void func2(std::packaged_task<double(int, char)> p) 47 { 48 p(3, 'a'); 49 try 50 { 51 p(3, 'c'); 52 } 53 catch (const std::future_error& e) 54 { 55 assert(e.code() == make_error_code(std::future_errc::promise_already_satisfied)); 56 } 57 } 58 59 void func3(std::packaged_task<double(int, char)> p) 60 { 61 try 62 { 63 p(3, 'a'); 64 } 65 catch (const std::future_error& e) 66 { 67 assert(e.code() == make_error_code(std::future_errc::no_state)); 68 } 69 } 70 71 int main() 72 { 73 { 74 std::packaged_task<double(int, char)> p(A(5)); 75 std::future<double> f = p.get_future(); 76 std::thread(func0, std::move(p)).detach(); 77 assert(f.get() == 105.0); 78 } 79 { 80 std::packaged_task<double(int, char)> p(A(5)); 81 std::future<double> f = p.get_future(); 82 std::thread(func1, std::move(p)).detach(); 83 try 84 { 85 f.get(); 86 assert(false); 87 } 88 catch (const A& e) 89 { 90 assert(e(3, 'a') == 106); 91 } 92 } 93 { 94 std::packaged_task<double(int, char)> p(A(5)); 95 std::future<double> f = p.get_future(); 96 std::thread t(func2, std::move(p)); 97 assert(f.get() == 105.0); 98 t.join(); 99 } 100 { 101 std::packaged_task<double(int, char)> p; 102 std::thread t(func3, std::move(p)); 103 t.join(); 104 } 105 } 106