std::future and std::promise of C++11

Why did C++11 introduce std::future and std::promise? After C++11 creates a thread, we cannot get the result directly from thread.join(), we must define a variable, assign a value to this variable when the thread executes, and then execute join(), the process is relatively cumbersome.

  The thread library provides futures for accessing the results of asynchronous operations . std::promise is used to wrap a value to bind data to future, which is convenient for obtaining a value in thread function. The value is obtained indirectly through the future provided inside promise, that is to say, the level of promise is higher than future high.


#include "stdafx.h"
#include <iostream>
#include <type_traits>
#include <future>
#include <thread>

using namespace std;
intmain()
{
    std::promise<int> promiseParam;
    std::thread t([](std::promise<int>& p)
    {
        std::this_thread::sleep_for(std::chrono::seconds(10));// thread sleep for 10s
        p.set_value_at_thread_exit(4);//
    }, std::ref(promiseParam));
    std::future<int> futureParam = promiseParam.get_future();

    auto r = futureParam.get();// block waiting outside the thread
    std::cout << r << std::endl;

    return 0;
}
 When the above program is executed to futureParam.get(), there are two threads. The newly opened thread is sleeping for 10s, while the main thread is waiting for the exit value of the newly opened thread. This operation is blocked, that is, std::future and std::promise can also be used for thread synchronization to some extent.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763942&siteId=291194637