0

Suppose I create a thread like this:


void Function()
{
    // Do stuff


    // How do I delete the current thread? I have tried RAII, but it throws.
    // delete backgroundThread; // Can't do this, even in finalizer
}

backgroundThread = new std::thread(&Test::Function);

How can I delete backgroundThread? I can't use thread.join from where I create the background thread because that will block the UI.

ABCD Man
  • 79
  • 4
  • 2
    What do you mean when your are saying "delete thread"? Why do you do `new`? – 273K Sep 11 '20 at 19:37
  • My delete thread I mean release its resources by calling `delete backgroundThread` – ABCD Man Sep 11 '20 at 19:37
  • 4
    Use the method detach. No `new` and `delete` are needed. – 273K Sep 11 '20 at 19:38
  • @S.M. But if I use detach and i DONT use `new`, then wouldn't the thread be destroyed on exit of the fucntion? – ABCD Man Sep 11 '20 at 19:40
  • @ABCDMan Could you please clarify first why you need to do that? What is your goal? It sounds like a XY problem for me. – πάντα ῥεῖ Sep 11 '20 at 19:42
  • Of course it will not be destroyed. That's why the method detach exists. – 273K Sep 11 '20 at 19:42
  • [Quoting](https://en.cppreference.com/w/cpp/thread/thread/detach): *Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits.* The thread may still be running. It won't be stopped, but A) it doesn't sound like you want it stopped and B) you don't want to stop a thread with a hammer anyway. You want to politely ask it to exit. – user4581301 Sep 11 '20 at 19:48
  • This question is kind of a non-sequitur. A `std::thread` is deleted the same way any other object is. The catch is that a `std::thread` must be joined or detached before it goes out of scope. – AndyG Sep 11 '20 at 19:54
  • Maybe the [documentation for the destructor](https://en.cppreference.com/w/cpp/thread/thread/%7Ethread) is another useful resource? It lists the situations in which it is safe to destroy a `std::thread`. – JaMiT Sep 11 '20 at 20:42
  • You can check this post as well: https://stackoverflow.com/questions/12207684/how-do-i-terminate-a-thread-in-c11 – KimKulling Sep 12 '20 at 09:14

1 Answers1

0

The solution to this was suggested by S.M.:

std::thread().detach()
ABCD Man
  • 79
  • 4