std promise的使用

注意:正确的使用promise要必须知道它什么时候会抛出异常
enum class future_errc {
    broken_promise             = /* promise已被析构*/,
    future_already_retrieved   = /* get_future()多次 */,
    promise_already_satisfied  = /* set_value()多次 */,
    no_state                   = /* future.get()已经成功,后面又future.get()了一次 */
};

example:

#include 
#include 
#include 
#include 
#include 
#include 
#include 

static std::string  future_string[] =
{ "ready",
   "timeout",
   "deferred"
};

int main()
{
    auto func = [](std::shared_ptr> ptr) {
        std::cout << "[thread]" << ptr.use_count() << std::endl;
        std::cout << "[thread] will set_value after 4s" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(4));
        if (ptr != nullptr)
        {
            ptr->set_value(20);
            std::cout << "[thread] set value done111~ " << ptr.use_count() << std::endl;
            ptr = nullptr;
            std::cout << "[thread] set value done222~ " << ptr.use_count() << std::endl;
        }
    };

    std::thread th_;

    {
        //构建promise
        std::shared_ptr> sp = std::make_shared>();
        std::future future = sp->get_future();
        std::future_status status;

        //创建线程, 以智能指针方式传递
        //以普通指针传递会有特殊情况,主线程等待超时都没等到函数退出
        //就会析构promise,此后线程中调用promise->setValue()就会报错
        th_ = std::thread(func, sp);

        try
        {
            //设置10s内轮询查看当前future状态
            for (int i = 0; i < 10; ++i)
            {
                status = future.wait_for(std::chrono::seconds(1));
                std::cout << "[main] ---> current status:  " << future_string[static_cast(status)] << "\t" << i << "s" << std::endl;
                if (status == std::future_status::ready)
                {
                    std::cout << "[main get the promise result:   " << future.get() << std::endl;
                    break;  /*一定要退出,只能get一次,多次就会有异常*/
                }
            }
        }
        catch (const std::exception& e)
        {
            std::cerr << "error: " << e.what() << std::endl;
        }
        
                
        std::cout << "[main]  func will exit, start delete promise_________  " << sp.use_count() << std::endl;
    }

    th_.join();
    return 0;
}
image.png

你可能感兴趣的:(std promise的使用)