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