C++ Concurrency Guide <future> (1) std::promise

The <future> header file contains the following classes and functions:

  1. Providers 类:std::promise, std::package_task
  2. Futures 类:std::future, shared_future.
  3. Providers function: std::async()
  4. 其他类型:std::future_error, std::future_errc, std::future_status,
    std::launch.

Introduction to the std::promise class

A promise object can store a value of a certain type T, which can be read by a future object (possibly in another thread), so promises also provide a means of thread synchronization. When the promise object is constructed, it can be associated with a shared state (usually std::future), and a value of type T can be stored on the associated shared state (std::future).
You can get the future object associated with the promise object through get_future. After calling this function, the two objects share the same shared state.

  • The promise object is an asynchronous provider, which can set the value of the shared state at a certain moment.
  • The future object can return the value of the shared state asynchronously, or if necessary, block the caller and wait for the shared state flag to become ready before obtaining the value of the shared state.

Here is a simple example to illustrate the above relationship:

#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

void print_int(std::future<int>& fut) {
    
    
    int x = fut.get(); // 获取共享状态的值.
    std::cout << "value: " << x << '\n'; // 打印 value: 10.
}

int main ()
{
    
    
    std::promise<int> prom; // 生成一个 std::promise<int> 对象.
    std::future<int> fut = prom.get_future(); // 和 future 关联.
    std::thread t(print_int, std::ref(fut)); // 将 future 交给另外一个线程t.
    
    prom.set_value(10); // 设置共享状态的值, 此处和线程t保持同步.
    std::cout << "set value 10" << std::endl;
    
    t.join();
    
    return 0;
}

std::promise constructor

default promise();
with allocator template promise (allocator_arg_t aa, const Alloc& alloc);
copy [deleted] promise (const promise&) = delete;
move promise (promise&& x) noexcept;
  1. The default constructor initializes an empty shared state.
  2. The constructor with a custom memory allocator is similar to the default constructor, but uses a custom allocator to allocate shared state.
  3. The copy constructor is disabled.
  4. Move constructor.

In addition, operator= of std::promise has no copy semantics, that is, ordinary assignment operations of std::promise are disabled, and operator= has only move semantics, so std::promise objects are forbidden to copy.

example:

#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

std::promise<int> prom;

void print_global_promise() {
    
    
    std::future<int> fut = prom.get_future();
    int x = fut.get();
    std::cout << "value: " << x << '\n';
}

int main()
{
    
    
    std::thread th1(print_global_promise);
    prom.set_value(10);
    th1.join();

    prom = std::promise<int>();    // prom 被move赋值为一个新的 promise 对象.

    std::thread th2 (print_global_promise);
    prom.set_value (20);
    th2.join();

    return 0;
}

std::promise::get_future 介绍

This function returns a future associated with the shared state of the promise. The returned future object can access the value set on the shared state by the promise object or an exception object. Only one future object can be obtained from the promise shared state. After calling this function, the promise object is usually ready at a certain point in time (set a value or an exception object). If the value or exception is not set, the promise object will automatically set a future_error exception (broken_promise) when it is destructed To set its own ready state. The get_future has been mentioned in the above example, so I won’t repeat it here.

Introduction to std::promise::set_value

Set the value of the shared state, after which the shared state flag of the promise becomes ready.

Introduction to std::promise::set_exception

Set an exception for the promise. After that, the shared state of the promise becomes ready. For example, thread 1 receives an integer from the terminal, and thread 2 prints the integer. If thread 1 receives a non-integer, then set an exception for the promise ( failbit), thread 2 throws the exception in std::future::get.

#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception

void get_int(std::promise<int>& prom) {
    
    
    int x;
    std::cout << "Please, enter an integer value: ";
    std::cin.exceptions (std::ios::failbit);   // throw on failbit
    try {
    
    
        std::cin >> x;                         // sets failbit if input is not int
        prom.set_value(x);
    } catch (std::exception&) {
    
    
        prom.set_exception(std::current_exception());
    }
}

void print_int(std::future<int>& fut) {
    
    
    try {
    
    
        int x = fut.get();
        std::cout << "value: " << x << '\n';
    } catch (std::exception& e) {
    
    
        std::cout << "[exception caught: " << e.what() << "]\n";
    }
}

int main ()
{
    
    
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();

//    std::thread th1(get_int, std::ref(prom));
    std::thread th2(print_int, std::ref(fut));
    std::thread th1(get_int, std::ref(prom));

    th1.join();
    th2.join();
    
    return 0;
}

std::promise::set_value_at_thread_exit 介绍

Set the value of the shared state, but do not set the flag of the shared state to ready, the promise object will be automatically set to ready when the thread exits. If a std::future object is associated with the shared state of the promise object, and the future is calling get, the thread calling get will be blocked. When the thread exits, the thread calling future::get will be unblocked, and at the same time get returns the value set by set_value_at_thread_exit. Note that this function has already set the value of the promise shared state. If there are other operations to set or modify the value of the shared state before the thread ends, future_error( promise_already_satisfied) will be thrown.

Introduction to std::promise::swap

Exchange the shared state of promises.

Guess you like

Origin blog.csdn.net/qq_24649627/article/details/114139029