boost :: thread中断异步

时间:2015-07-23 23:54:19

标签: c++ multithreading boost

我想在交换机中使用线程。这可能还是有另一种方法来中断程序中其他地方的线程?

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;
}

谢谢。

2 个答案:

答案 0 :(得分:1)

您需要做的是将此线程对象作为相应类的成员变量,以便可以在此类的函数调用之间共享。

如,

#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;
};

答案 1 :(得分:1)

我想通了,感谢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;
}

我知道答案比创建一个复杂的类更简单。