C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::shared_ptr resurrect

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Tue, 12 Dec 2023 15:26:06 +0000
On Mon, 2023-12-11 at 14:00 +0200, Valentin Palade via Std-Proposals
wrote:
> Hello Everyone,
> I would like your opinion on a small addition to the std::shared_ptr:
>
> bool std::shared_ptr::resurrect();
>
> with the following behavior:
> * will atomically decrement the use counter and
> - if use counter != 0 will reset the shared_ptr instance and
> return false
> - otherwise, increment the use counter, leave the shared_ptr
> instance unchanged and return true (thus resurrecting the shared_ptr
> instance).
> Usage scenario:
> * producer creates a shared_ptr message to be sent to multiple
> consumers - threads/actors/connections
> * on consumers, we want to be able to return the shared_ptr message
> to the producer (e.g. to be reused), once consumed by all.
> Code sample:
> using SharedMessageT = std::shared_ptr<Message>;
> std::promise<SharedMessageT> p;
> auto f = p.get_future();
>
> vector<jthread> thr_vec;
> {
>
> auto sm = std::make_shared<Message>();
>
> auto lambda = [&p, sm]() mutable {
> doConsume(*sm);
>
> if (sm.resurrect()) {
> p.set_value(std::move(sm));
> }
> };
>
> for (size_t i = 0; i < 4; ++i) {
> thr_vec.emplace_back(lambda);
> }
>
> if (sm.resurrect()) {
> p.set_value(std::move(sm));
> }
> }
> {
> auto sm = f.get();
> doReuse(sm);
> }
>

How would resurrect() affect weak_ptr instances pointing to the same
object/control block? If they are not invalidated then they could lock
the weak_ptr and bump up the reference count back up above 1
immediately after a successful resurrect(). If they are invalidated
then I think you need to allocate a new control block to accomplish
that.

>
> Similar concept implemented
> here: https://github.com/solidoss/solidframe/blob/a54ef124ac77c97689c
> 5d9204be35936aaf85c26/solid/utility/sharedbuffer.hpp#L139
> And tested
> here: https://github.com/solidoss/solidframe/blob/a54ef124ac77c97689c
> 5d9204be35936aaf85c26/solid/utility/test/test_shared_buffer.cpp#L36
>
> Thanks,
> Valentin Palade
>

Received on 2023-12-12 15:26:13