It would be useful to have an AtomicUniquePtr<T> template
Categories
(Core :: MFBT, enhancement)
Tracking
()
People
(Reporter: jfkthame, Unassigned)
Details
I've recently written some patches that replace usage of UniquePtr<T> with Atomic<T*>, which is useful for multi-threaded code to be able to check the value of the pointer without locking; but it loses the lifetime-management benefit of UniquePtr.
It would be nice to have a type that works like UniquePtr but with the added feature of atomic access to the pointer value. (Not to what it points at, obviously.)
It sounded like a good idea to me, and I wondered why it was not already standard, when std::atomic<std::shared_ptr> is there (in C++20)...
I found a good explanation: In summary, it's because unique_ptr and our UniquePtr allow for an optional user-provided pointer to a destructor, and it's not possible (or reasonable to expect) to do atomic operations on two pointers together.
But maybe it would still be useful in most use cases to have an AtomicUniquePtr<T> with no deleter? Or even AtomicUniquePtr<T, D> where we don't need to keep a pointer to a D?
I'll be following this bug with interest. 🤓
(In reply to Gerald Squelart [:gerald] (he/him) from comment #1)
it's not possible (or reasonable to expect) to do atomic operations on two pointers together.
Coincidentally: https://timur.audio/dwcas-in-c -- most modern chips actually have double-width compare-and-swap instructions! 😅 But it still looks like hard work, with no official support in C++.
| Reporter | ||
Comment 3•4 years ago
|
||
Yeah, I realize it would be difficult to implement everything UniquePtr does in an Atomic version. For now, at least, I'd find it sufficiently useful to have a simple AtomicUniquePtr<T> that doesn't support custom destructors at all, just calls delete on its target. (I guess an array specialization that calls delete[] might not be a problem, though I haven't yet wanted it.)
Comment 4•4 years ago
|
||
(In reply to Jonathan Kew (:jfkthame) from comment #0)
I've recently written some patches that replace usage of UniquePtr<T> with Atomic<T*>, which is useful for multi-threaded code to be able to check the value of the pointer without locking
This is, of course, wildly unsafe in the general case:
- Thread B gets the pointer out of the
Atomic<T*>. - Thread A atomic-exchanges the
Atomic<T*>withnullptr(or some otherT*) and destroys theTbehind it. - Thread B attempts to access the already-freed
Tthrough the pointer it just acquired.
How do you avoid this situation?
(There are several possible answers to that question; each of them suggests a different data type that formalizes it.)
Description
•