c++multithreadingfuture

Can multiple threads copy a std::shared_future at the same time?


Is a shared_lock enough in GetNextImage(), or do I need to use a unique_lock?

shared_future<Mat> shfutNextImage;
shared_mutex shmutNextImage;

shared_future<Mat> GetNextImage()
{
    shared_lock lock(shmutNextImage);
    return shfutNextImage;
}

void SetNextImage(shared_future<Mat> shfut)
{
    unique_lock lock(shmutNextImage);
    shfutNextImage = shfut;
}

Solution

  • Using shfutNextImage as an argument to the copy constructor from multiple threads is safe because the object is used as const& parameter, therefore you do not need a lock assuming no one modifies the object in the meantime -> shared/read lock is appropriate.

    Assigning to shfutNextImage from multiple threads is not safe I think so the unique_lock is appropriate. At least I do not see any explicit mentions that it is thread-safe. Other non-const methods like wait are also not thread-safe.

    Use shfutNextImage = std::move(shfut); if you can, to avoid unnecessary +1 (assignment), -1(destruction of shfut) to the reference counter. Copying shared futures is not cheap, you can image there is hidden std::shared_ptr<State> inside, so move is better.

    Accessing the Mat object the future holds is never thread-safe, the protection is left to the user.