dimanche 24 avril 2022

Cleanly exit Boost thread member of class

I have a class that has a boost::thread member variable. I have a private member function that is run in that thread (see code below).

class Human
{
  public:
    Human()
        : m_thinkThread(&Human::think, this)
    { }

    ~Human()
    {
        m_thinkThread.interrupt();
        m_thinkThread.join();
    }

  private:
    void think()
    {
        // do some thinking...
    }

    boost::thread m_thinkThread;
};
  1. Do I need the interrupt and join calls and therefore the custom destructor? Or will the default destructor take care of exiting cleanly? If the default destructor is all I need, then what does it do "under the hood" to ensure the thread is exited cleanly?
  2. If I do however, need the interrupt and join calls, then my current setup has a bug because join() can throw, which will be an uncaught exception in a destructor. How would I handle this case?

Thank you

Aucun commentaire:

Enregistrer un commentaire