2

Will a thread object be destroyed when its controlling smart pointer going out of scope.

For example, in the following code, will the threads still be running when process() function is being executed? My understanding is that, all the 50 threads will already get destroyed because their smart pointers t are going out of scope when process() function is being executed. Am I correct?

int main(){
  for (int i=0; i<50; i++){
    std::shared_ptr<MyRunner> sub(new MyRunner());   
    std::unique_ptr<Thread> t(new Thread(sub)); 
    t->start();
  }
  process();
}
user3462510
  • 106
  • 7

1 Answers1

1

I think you have it correctly. This is not really specific to "threads" as such, but more to the behaviour of unique_ptr which destroys its owned pointer when it goes out of scope. In your example, you could replace Thread with Banana and MyRunner with Apple and the behaviour in that sense would be the same.

Thanks. Then if I want to start 50 threads in a loop, and still use smart pointers to control the thread objects, how can I modify the above code? (is there a way to let the threads keep running even if their controlling smart pointers going out of scope)?

So far as threads are concerned, they will continue running regardless of whether the smart pointers have died or not. A better question might be to see how you can keep the smart pointers alive until the threads have finished running. To do this, you would need to know two things, the first being, how do you know when a thread has completed processing, and the second, how to keep a reference to multiple smart pointers.

To answer the first part would depend on the details of your underlying threading implementation so I can't speak to that in too much detail.

For the second, probably an array such as std::vector is going to be useful. You might like to refer to these questions for information on possible pitfalls of this approach:

So can unique_ptr be used safely in stl collections? Why can I not push_back a unique_ptr into a vector?

Community
  • 1
  • 1
1800 INFORMATION
  • 131,367
  • 29
  • 160
  • 239
  • Thanks. Then if I want to start 50 threads in a loop, and still use smart pointers to control the thread objects, how can I modify the above code? (is there a way to let the threads keep running even if their controlling smart pointers going out of scope)? – user3462510 Mar 26 '14 at 04:39
  • I added some more detail in the answer – 1800 INFORMATION Mar 26 '14 at 21:14