I have a worker thread giving my rendering thread a std::shared_ptr<Bitmap>
as part of how I download texture data from the GPU. Both threads depend on std::shared_ptr<...>::unique()
to determine if the other thread is done with the Bitmap. No other copies of this shared pointer are in play.
Here's a trimmed down chart of the behavior:
worker thread | rendering thread
----------------------------------- + -------------------------------------------------
std::shared_ptr<Bitmap> bitmap; | std::queue<std::shared_ptr<Bitmap>> copy;
{ | {
std::scoped_lock lock(mutex); | std::scoped_lock lock(mutex);
queue.push_back(bitmap); | std::swap(queue, copy);
} | }
... | for(auto it = copy.begin(); it != copy.end(); ++it)
| if (it->unique() == false)
if (bitmap.unique()) | fillBitmap(*it); // writing to the bitmap
bitmap->saveToDisk(); // reading
Is it safe to use unique()
or use_count() == 1
to accomplish this?
edit:
Ah... since unique()
is unsafe in this case, I think instead I'm going to try something like std::shared_ptr<std::pair<Bitmap, std::atomic<bool>>> bitmap;
instead, flipping the atomic when it's filled.