jeudi 30 mars 2017

Is it required to keep promise valid when using its future?

Say I have a function that enqueues a job and returns an std::future that will be set when the job is done. Is it required to keep the corresponding std::promise valid?

std::vector<std::promise<void>> jobs;
std::mutex jobMutex;

std::future<void> EnqueueJob()
{
    std::lock_guard<std::mutex> lock(jobMutex);
    jobs.emplace_back();
    return jobs.back().get_future();
}

// async job loop
void DoJobs()
{
    while(true)
    {
        // (...) wait for a job to be ready

        // finish jobs
        std::lock_guard<std::mutex> lock(jobMutex);
        // (...)
        for (auto& promise : jobs)
            promise.set_value();
        jobs.clear();
    }
}

If I enqueue a job and wait for its future later on it is possible that the corresponding promise is already cleared from the job vector. Is this okay? If not, what would be a good way to solve this problem?

I am unable to find an answer using promise's and future's documentation.

Aucun commentaire:

Enregistrer un commentaire