C++
std::promise
concurrency
multithreading
asynchronous-programming

What is stdpromise?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Overview

std::promise is a feature introduced in C++11 as part of the Standard Library's support for concurrency. It is an important part of the <future> header, designed to help manage asynchronous operations through a mechanism that decouples the production of a value from its consumption. At the core, std::promise allows a producer thread to "promise" a result will be made available, while a consumer thread uses a std::future to access that result.

Detailed Explanation

Here's a technical dive into what std::promise and std::future are and how they work together:

Key Concepts

  • std::promise:
    • Purpose: Used by the producer to set a value or an exception that will be communicated to a std::future.
    • Member Functions:
      • set_value(T value): Sets the promised value.
      • set_exception(std::exception_ptr exception): Communicates an exception to the std::future.
      • get_future(): Returns the associated std::future.
  • std::future:
    • Purpose: Used by the consumer to retrieve the result of an asynchronous operation set by a std::promise.
    • Member Functions:
      • get(): Retrieves the value, potentially blocking if the value isn't available yet.
      • wait(): Blocks until the result is available.
      • valid(): Checks if the std::future has a shared state.

Basic Example

Asynchronous programming benefits from std::promise and std::future. Below is a simple example demonstrating their usage:

cpp
1#include <iostream>
2#include <thread>
3#include <future>
4
5void perform_task(std::promise<int> prm) {
6    // Simulate a task that calculates a result
7    int result = 42; // Example computation
8    std::this_thread::sleep_for(std::chrono::seconds(2)); // Simulate work
9    prm.set_value(result); // Set the value for the associated future
10}
11
12int main() {
13    std::promise<int> promise;
14    std::future<int> future = promise.get_future();
15
16    std::thread worker(perform_task, std::move(promise));
17
18    std::cout << "Waiting for the result...\n";
19    int result = future.get(); // This will block until the promise is fulfilled
20    std::cout << "The result is: " << result << std::endl;
21
22    worker.join();
23    return 0;
24}

Handling Exceptions

std::promise can also communicate exceptions to a std::future. This ensures that the calling code can handle errors appropriately.

cpp
1#include <iostream>
2#include <thread>
3#include <future>
4#include <stdexcept>
5
6void perform_task_with_exception(std::promise<int> prm) {
7    try {
8        throw std::runtime_error("Something went wrong!");
9    } catch (...) {
10        prm.set_exception(std::current_exception());
11    }
12}
13
14int main() {
15    std::promise<int> promise;
16    std::future<int> future = promise.get_future();
17
18    std::thread worker(perform_task_with_exception, std::move(promise));
19
20    try {
21        int result = future.get();
22    } catch (const std::exception &e) {
23        std::cout << "Caught exception: " << e.what() << std::endl;
24    }
25
26    worker.join();
27    return 0;
28}

Advanced Usage

You can use std::promise in more advanced scenarios involving multiple threads and synchronization mechanisms. Some sophisticated tasks might involve:

  • Thread Pools: Using std::promise and std::future to manage thread return values.
  • Parallel Algorithms: Facilitating communication among threads performing parallel computations.
  • Condition Variables: While std::promise and std::future implicitly manage synchronization, sometimes explicit use of std::condition_variable may improve efficiency in certain designs.

Summary Table

FeatureDescription
std::promiseDecouples value production from consumption
set_valueSet the transmitted value to a future
set_exceptionSet an exception to communicate an error
get_futureRetrieve the associated std::future
std::futureRetrieves values from asynchronous operations
getBlocks until value is available; retrieves it
waitBlocks until result is available
validChecks if future has a shared state

Conclusion

std::promise and std::future provide a powerful mechanism for managing asynchronous operations in C++. They enable a producer-consumer model that is crucial for concurrent and parallel applications, ensuring that values and exceptions can be communicated seamlessly across threads. By understanding and using these abstractions, developers can write more responsive and efficient applications designed to leverage multi-threading capabilities.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.