Non-obvious lifetime issue with std::promise and std::future

后端 未结 4 1862
[愿得一人]
[愿得一人] 2021-02-05 18:10

This question is very similar to a previous one here: race-condition in pthread_once()?

It is essentially the same issue - the lifetime of a std::promise en

4条回答
  •  轮回少年
    2021-02-05 18:21

    std::promise is just like any other object: you can only access it from one thread at a time. In this case, you are calling set_value() and destroying the object from separate threads without sufficient synchronization: nowhere in the spec does it say that set_value will not touch the promise object after making the future ready.

    However, since this future is used for a one-shot synchronization, you don't need to do that anyway: create the promise/future pair right in run(), and pass the promise to the thread:

    struct synchronous_job
    {
        synchronous_job(std::function job, dispatcher& d)
            : _job(job)
            , _d(d)
        {
        }
        void run(){
            std::promise p;
            std::future f=p.get_future();
    
            _d.post(
                [&]{
                    cb(std::move(p));
                });
    
            f.wait();
        }
    private:
        void cb(std::promise p)
        {
            _job();
            p.set_value();
        }
        std::function _job;
        dispatcher&           _d;
    };
    

提交回复
热议问题