asterx
asterx

Reputation: 85

shared_ptr reference counting when spawning a std::thread

I'm a little new to multithreading in C++11 and I have a specific question on spawning std::threads as shown below. Notes is a class with a public method start in it. And thread_list is a vector holding std::threads.

void spawn()
{
    std::shared_ptr<Notes> note = std::make_shared<Notes>();
    std::thread thrd(&Notes::start, note);
    thread_list.push_back(std::move(thrd));
}

My question is who owns the shared_ptr note after this function finishes? Does reference to the thread thrd count as a reference and hence the shared_ptr does not destruct the object reference? Any clarification would be greatly appreciated.

Upvotes: 1

Views: 92

Answers (1)

Cornstalks
Cornstalks

Reputation: 38238

My question is who owns the shared_ptr note after this function finishes?

thrd owns it, in a way. But not really. Read on for what really happens.

Does reference to the thread thrd count as a reference and hence the shared_ptr does not destruct the object reference?

Kind of, but not really. thrd doesn't actually count as a reference, and actually doesn't share ownership of note. It's just a handle to a thread.

So who owns note? The Notes::start function does.

You've started a thread that is executing Notes::start, and have passed notes to that function. That function now owns notes.

If thrd goes out of scope, notes will still exist so long as the Notes::start function hasn't exited and hasn't relinquished ownership of notes.

Upvotes: 3

Related Questions