On 2/10/2020 2:04 PM, Chris M. Thomasson wrote:
> On 2/10/2020 6:23 AM, Bonita Montero wrote:
>>>> I posted everything to understand the issue.
>>>> The code is sufficient and the description of the question as well.
>>>> And I see you didn't understand it.
>>
>>> The onus on the understandability of text is on the writer, not the
>>> reader.
>>
>> The people on Stack Overflow understood it.
>>
>
> // pseudo code, sorry for any typos:
>
>
> void foo(shared_ptr<bar> ptr)
> {
> shared_ptr<bar> tptr = ptr;
>
> // create thread using tptr
> }
>
>
> // call foo with a temporary
> foo(shared_ptr<bar>(new bar()));
>
>
> iirc, works fine. the tptr in the function foo has a reference,
> therefore the refcount is bumped accordingly. You can create a thread
> using tptr.
You can package tptr up in a struct: a thread descriptor that has a
shared_ptr<bar> member to store it in. This maintains the reference
count, start the thread, and it has that reference, fine. The reference
was bumped _before_ the thread was started. You can store it in a
"message" struct and enqueue it such that other threads can dequeue it.
The reference was bumped _before_ another thread has a chance to grab
it. Just keep in mind that shared_ptr requires that a thread has a prior
reference before it can access it. In other words, shared_ptr provides
basic thread safety, not strong, at least last time I used it. pseudo-code:
This is bad wrt shared_ptr:
static shared_ptr<bar> g_bar; // nullptr
void multiple_threads()
{
for (;;)
{
// this does not work wrt the
// last time I looked at shared_ptr
shared_ptr<bar> local = g_bar;
local->foobar();
}
}
void single_thread()
{
shared_ptr<bar> local(new bar());
g_bar = local;