example5_asynchronous_callbacks_with_threads.cpp

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

// A function that simulates an asynchronous task and uses a callback
void asyncTask(int x, std::function<void(int)> callback) {
    std::thread([=]() {
        std::this_thread::sleep_for(std::chrono::seconds(2));  // Simulate a delay
        callback(x * 2);  // Invoke the callback after the delay
    }).detach();  // Detach the thread to run independently
}

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

    asyncTask(5, [](int result) {
        std::cout << "Async task completed with result: " << result << std::endl;
    });

    std::this_thread::sleep_for(std::chrono::seconds(3));  // Wait for the async task to complete
    return 0;
}
Back to callbacks