example1_async_function.cpp

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

int longComputation(int x) {
    std::this_thread::sleep_for(std::chrono::seconds(3));  // Simulate a long computation
    return x * x;
}

int main() {
    std::cout << "Starting async task..." << std::endl;

    // Start the longComputation function asynchronously
    std::future<int> result = std::async(std::launch::async, longComputation, 10);

    std::cout << "Doing other work in main thread..." << std::endl;

    // Get the result from the async task (this will block if the task is not finished)
    int value = result.get();

    std::cout << "Result from async task: " << value << std::endl;

    return 0;
}
Back to std_async