example4_using_async.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <future>
#include <chrono>

int compute_value() {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}

int main() {
    std::cout << "Starting async operation..." << std::endl;
    
    std::future<int> result = std::async(std::launch::async, compute_value);
    
    std::cout << "Doing other work..." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    
    std::cout << "Result is: " << result.get() << std::endl;
    
    return 0;
}
Back to thread