Date: Mon, 11 Dec 2023 13:24:30 -0700
On Monday, 11 December 2023 12:42:23 MST Marcin Jaczewski wrote:
> > But if it's 1, then you have the only copy and there is no other thread
> > seeing this object. The number can't change unless the current thread
> > changes it.
> But all threads can return 5 too. As check is done before decrement
> every one can observe the state before it.
Correct. All of them can observe the state as 5. That means all of them could
decrement and you'd get a discarded block, instead of reusing it.
> And this means no thread can get 1 and acquire the last instance.
> We need to guarantee that one thread will be the least instance.
Do you really need to guarantee that? This problem sounded like an
optimisation to reuse pre-allocated buffers, not a requirement.
If you REALLY need to, then yes, use_count() won't solve your problem. But I'd
question your assertion that you really must. At that point, maybe you should
rearchitect to remove the extra indirection via shared_ptr and use an
intrusive ref-count that you control. You probably don't need shared_ptr's
other feature of not incrementing up from 0.
Or use a mutex.
> > But if it's 1, then you have the only copy and there is no other thread
> > seeing this object. The number can't change unless the current thread
> > changes it.
> But all threads can return 5 too. As check is done before decrement
> every one can observe the state before it.
Correct. All of them can observe the state as 5. That means all of them could
decrement and you'd get a discarded block, instead of reusing it.
> And this means no thread can get 1 and acquire the last instance.
> We need to guarantee that one thread will be the least instance.
Do you really need to guarantee that? This problem sounded like an
optimisation to reuse pre-allocated buffers, not a requirement.
If you REALLY need to, then yes, use_count() won't solve your problem. But I'd
question your assertion that you really must. At that point, maybe you should
rearchitect to remove the extra indirection via shared_ptr and use an
intrusive ref-count that you control. You probably don't need shared_ptr's
other feature of not incrementing up from 0.
Or use a mutex.
-- Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org Software Architect - Intel DCAI Cloud Engineering
Received on 2023-12-11 20:24:58