【问题标题】:wxwidgets - exit the thread the right waywxwidgets - 以正确的方式退出线程
【发布时间】:2011-08-02 12:43:23
【问题描述】:

我运行 openCL /openGL 程序,它使用 wxWidget 作为 gui 环境

在派生自 wxThread 的类的对象内部,我执行了一些复杂的计算并构建了许多 openCL 程序。 我想删除线程。但是线程并没有立即删除——它会继续构建程序,并且在完成所有编译之后。

我知道我可以使用wxThread::KIll() 退出线程,但它会导致一些内存问题,所以它不是一个真正的选择。

我有从 wxFrame 派生的 myFrame 类。它有 pCanvas 指针,它指向从 wxCanvas 派生的对象 *pCanvas 对象包括 myThread(运行复杂的计算)

void myFrame::onExit(wxCommandEvent& WXUNUSED(event))
{
       if(_pCanvas != NULL )
       {
              wxCriticalSectionLocker enter(_smokeThreadCS);
              // smoke thread still exists
              if (_pCanvas->getThread() != NULL)
              {
                     //_pCanvas->getSmokeThread()->Delete(); <-waits until thread ends and after it application terminates
                     _pCanvas->getSmokeThread()->Kill();     <- immediately makes the application not responding
              }
       }
       // exit from the critical section to give the thread
       // the possibility to enter its destructor
       // (which is guarded with m_pThreadCS critical section!)

       while (true)
       {
              { // was the ~MyThread() function executed?
                     wxCriticalSectionLocker enter(_smokeThreadCS);
                     if (!_pCanvas->getSmokeThread()) break;
              }

              // wait for thread completion
              wxThread::This()->Sleep(1);
       }
       DestroyChildren();
       Destroy();
       // Close the main frame, this ends the application run:
       Close(true);
}

【问题讨论】:

  • IIUC 线程获取临界区并进行杀戮不是线程被杀吗?
  • 杀死这样的线程并不是一个好主意。

标签: c++ multithreading visual-studio-2010 wxwidgets


【解决方案1】:

杀死这样的线程确实非常糟糕。最好给线程一个清理的机会。

优雅的线程终止通常是通过定期检查一个告诉它退出的标志来完成的:

volatile bool continue_processing = true;
thread thread;

void compile_thread()
{
    while(continue_processing)
    {
        // compile one OpenCL program.
    }
}

void terminate()
{
    read_write_barrier();
    continue_processing = false;
    write_barrier();

    thread.join(); // wait for thread to exit itself.
}

根据您的 CPU 和编译器,仅将 continue_processing 标记为 volatile 可能不足以使更改立即发生并对其他线程可见,因此使用了屏障。

您必须查阅编译器的文档以了解如何创建屏障……它们各不相同。 VC++ 使用_ReadWriteBarrier()_WriteBarrier()

【讨论】:

    【解决方案2】:

    如果它是不可连接的线程,它会自行死亡并清理

    编辑:

    我找到了this link,我认为这会很有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 1970-01-01
      • 2011-12-22
      • 2013-09-27
      相关资源
      最近更新 更多