xinthose
xinthose

Reputation: 3820

boost::thread interrupt asynchronously

I would like to use threads in a switch. Is this possible or is there another way to interrupt the thread elsewhere in the program?

switch (event_element)    // dispatch event handler
{
    case 1: // main task thread
    {
        boost::thread thr_check_db_task (check_db_task);
        break;
    }
    case 2:
    {
        std::cerr << "DATABASE CONNECTION ERROR" << std::endl;
        thr_check_db_task.interrupt ();        // **COMPILE ERROR**
        mysql_connection_error ();
        break;
    }
    default:
        break;
}

Thank you.

Upvotes: 1

Views: 132

Answers (2)

xinthose
xinthose

Reputation: 3820

I figured it out, thanks to this question.

boost::thread thr_check_db_task;

switch (event_element)    // dispatch event handler
{
    case 1: // main task thread
    {
        thr_check_db_task = boost::thread (check_db_task);
        break;
    }
    case 2:
    {
        std::cerr << "DATABASE CONNECTION ERROR" << std::endl;
        thr_check_db_task.interrupt ();
        mysql_connection_error ();
        break;
    }
    default:
        break;
}

I knew the answer was simpler than creating a complex class.

Upvotes: 1

Eric Z
Eric Z

Reputation: 14505

What you need to do is to put this thread object as a member variable of the according class so that it can be shared among function calls of this class.

E.g.,

#include <boost/thread/thread.hpp>

class tMyApp
{
   struct callable
   {
      void operator()()
      {
         // Do something and wait to be interrupted
         while (true)
         {
            /* .. */
         }
      }
   };

public:
   tMyApp(): m_thread(m_threadProc)
   {
      /* do something.. */

      m_thread.interrupt();
   }

private:
   callable m_threadProc;
   // The thread object
   boost::thread m_thread;
};

Upvotes: 1

Related Questions