intmain(){ // Demonstrate using promise<int> to transmit a result between threads. std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 }; std::promise<int> accumulate_promise; std::future<int> accumulate_future = accumulate_promise.get_future(); std::thread work_thread(accumulate, numbers.begin(), numbers.end(), std::move(accumulate_promise));
// future::get() will wait until the future has a valid result and retrieves it. // Calling wait() before get() is not needed // accumulate_future.wait(); // wait for result accumulate_future.wait(); std::cout << "2 result=" << accumulate_future.get() << '\n'; work_thread.join(); // wait for thread completion
// Demonstrate using promise<void> to signal state between threads. std::promise<double> barrier; std::future<double> barrier_future = barrier.get_future(); std::cout << "3 before running thread do work." << std::endl;
std::thread new_work_thread(do_work, std::move(barrier)); std::cout << "4 after unning thread do work. barrier_future.wait(); " << std::endl;