C++ Logo

std-proposals

Advanced search

Re: [std-proposals] A non-owning but self zeroing smart pointer for single ownership

From: JOHN MORRISON <inglesflamenco_at_[hidden]>
Date: Fri, 21 Feb 2025 22:28:48 +0000
Tiago,

You are right in a saying that thread ownership isn't a thing. There is only thread execution and that is why the compiler can't help here and there is no declarative solution. It is also true that a unique_ptr doesn't necessarily run in the thread in which it is created. The thread checking mechanism does anticipate that. It associates a thread id with a unique_ptr<T, notify_ptrs<T> > when the first ptr_to_unique is taken from it and a control block is allocated. That works out quite well. I have been wanting to share how this works:

For thread A to pass a ptr_to_unique to thread B, thread A first has to create a ptr_to_unique to pass which causes a control block to be allocated stamped with thread A. Trying to use it from thread B will trigger an exception.

When thread A moves or swaps a unique_ptr<T, notify_ptrs<T> > held object into thread B, the move or swap is carried out by thread A but all ptr_to_uniques that reference it are zeroed. It is virgin again and no longer associated with a control block. There won't be one to stamp until it is running in thread B and a ptr_to_unique is taken from. It will then create a control block stamped with thread B and all use from thread B will work as expected.

I thinks its cool because it stops what you don't want to happen but doesn't impede what you do want to happen …... as far I have been able to anticipate. But its logic is circumstantial and doesn't have a solid foundation. It is a band aid just to stop you doing the wrong thing and there is something lame about that. That exception will only hit you once. After that you won't go there again.

I believe you when you say that it will be rejected for that.

Perhaps the correct way to look at it is to say that ptr_to_unique works with unique_ptr (declared with the notify_ptrs deleter), a unique_ptr can only have single thread visibility and we have always had to conform to this. So there you have clear domain of safe use where your use of unique_ptr will already be sitting and where the use cases can be found.

If you want data to be safely visible to multiple threads then it must have shared ownership and you will be using shared_ptr/weak_ptr for that, not unique_ptr.

So why complain that ptr_to_unique can't do threadsafe cross thread dereferencing when a unique_ptr is never put in that position and we already have shared_ptr/weak_ptr to do that. It is like complaining that a cat doesn't bark.

I like that argument but how do others see it? Has the concern about thread safety just been a knee jerk reaction that missed the point?

I am not quite sure where to leave it. I will spend more time thinking about it and listen to what others have to say


Received on 2025-02-21 22:28:51