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
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;
};