Futures and Promises
Safely passing results between threads is a common challenge. The standard library provides two powerful tools for this purpose: std::promise and std::future. These classes work together to synchronize result delivery between threads, ensuring that data produced in one thread can be reliably retrieved in another thread without the risk of race conditions or data corruption.
A std::promise acts as a write-end for a value that will be computed asynchronously. It is typically created in the main thread and passed to a worker thread. The worker thread performs some computation and, when finished, sets the result using the promise. The std::future is the read-end, obtained from the promise. The main thread can then wait for the computation to finish and retrieve the result via the future. This mechanism guarantees that the main thread will block if it tries to access the result before it is ready, thus synchronizing the threads safely.
main.cpp
1234567891011121314151617181920212223242526272829#include <iostream> #include <thread> #include <future> // Function that simulates a long computation and sets the result in a promise void worker(std::promise<int> resultPromise) { int result = 42; // Simulate some computation std::this_thread::sleep_for(std::chrono::seconds(1)); // Simulate delay resultPromise.set_value(result); // Deliver result to main thread } int main() { // Create a promise and obtain its future std::promise<int> myPromise; std::future<int> myFuture = myPromise.get_future(); // Start a worker thread, passing the promise by move std::thread t(worker, std::move(myPromise)); // Main thread waits for the result std::cout << "Waiting for result from worker thread..." << std::endl; int value = myFuture.get(); // Will block until worker sets the value std::cout << "Result received: " << value << std::endl; t.join(); // Clean up the thread }
In C++ concurrency:
- A future is an object that can retrieve a value set asynchronously, usually by another thread;
- A promise is an object that allows a value to be set at a later time, which can then be obtained through a future.
Using std::promise and std::future together allows you to safely transfer results from one thread to another, ensuring that the receiving thread waits until the result is actually available. This synchronization is crucial for avoiding race conditions and for writing robust concurrent code.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you show an example of how to use std::promise and std::future in code?
What are some common mistakes to avoid when using std::promise and std::future?
Are there alternatives to std::promise and std::future for thread synchronization?
Awesome!
Completion rate improved to 7.69
Futures and Promises
Свайпніть щоб показати меню
Safely passing results between threads is a common challenge. The standard library provides two powerful tools for this purpose: std::promise and std::future. These classes work together to synchronize result delivery between threads, ensuring that data produced in one thread can be reliably retrieved in another thread without the risk of race conditions or data corruption.
A std::promise acts as a write-end for a value that will be computed asynchronously. It is typically created in the main thread and passed to a worker thread. The worker thread performs some computation and, when finished, sets the result using the promise. The std::future is the read-end, obtained from the promise. The main thread can then wait for the computation to finish and retrieve the result via the future. This mechanism guarantees that the main thread will block if it tries to access the result before it is ready, thus synchronizing the threads safely.
main.cpp
1234567891011121314151617181920212223242526272829#include <iostream> #include <thread> #include <future> // Function that simulates a long computation and sets the result in a promise void worker(std::promise<int> resultPromise) { int result = 42; // Simulate some computation std::this_thread::sleep_for(std::chrono::seconds(1)); // Simulate delay resultPromise.set_value(result); // Deliver result to main thread } int main() { // Create a promise and obtain its future std::promise<int> myPromise; std::future<int> myFuture = myPromise.get_future(); // Start a worker thread, passing the promise by move std::thread t(worker, std::move(myPromise)); // Main thread waits for the result std::cout << "Waiting for result from worker thread..." << std::endl; int value = myFuture.get(); // Will block until worker sets the value std::cout << "Result received: " << value << std::endl; t.join(); // Clean up the thread }
In C++ concurrency:
- A future is an object that can retrieve a value set asynchronously, usually by another thread;
- A promise is an object that allows a value to be set at a later time, which can then be obtained through a future.
Using std::promise and std::future together allows you to safely transfer results from one thread to another, ensuring that the receiving thread waits until the result is actually available. This synchronization is crucial for avoiding race conditions and for writing robust concurrent code.
Дякуємо за ваш відгук!