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

后端 未结 4 1774
[愿得一人]
[愿得一人] 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:30

    Answering my own question, to offer a workable solution. It doesn't use std::promise or std::future, but it achieves the synchronisation which I'm searching for.

    Update synchronous_job to use a std::condition_variable and std::mutex instead:

    Edit: Updated to include a boolean flag as suggested by Dave S

    struct synchronous_job
    {
        synchronous_job(std::function job, dispatcher& d)
            : _job(job)
            , _d(d)
            , _done(false)
        {
        }
        void run()
        {
            _d.post(std::bind(&synchronous_job::cb, this));
            std::unique_lock l(_mtx);
            if (!_done)
                _cnd.wait(l);
        }
    private:
        void cb()
        {
            _job();
            std::unique_lock l(_mtx);
            _done = true;
            _cnd.notify_all();
        }
        std::function   _job;
        dispatcher&             _d;
        std::condition_variable _cnd;
        std::mutex              _mtx;
        bool                    _done;
    };
    

提交回复
热议问题