wxwidgets - 以正确的方式退出线程
我运行 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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样杀死一个线程确实是非常糟糕的。最好给线程一个清理的机会。
优雅的线程终止通常是通过定期检查告诉它退出的标志来完成的:
根据您的 CPU 和编译器,简单地将
Continue_processing
标记为易失性
可能不足以使更改会立即发生并且对其他线程可见,因此使用了屏障。您必须查阅编译器的文档以了解如何创建屏障......它们各自不同。 VC++ 使用
_ReadWriteBarrier()
和_WriteBarrier()
。Killing a thread like that is indeed very bad. It's best to give the thread a chance to clean up.
Graceful thread termination is usually done by periodically checking a flag that tells it to exit:
Depending on your CPU and compiler, simply marking
continue_processing
asvolatile
might not be enough to make the change happen immediately and visible to the other thread, so barriers are used.You'll have to consult your compiler's documentation to see how to create a barrier... they're different in each one. VC++ uses
_ReadWriteBarrier()
and_WriteBarrier()
.如果它是不可连接的线程,它会自行死亡并清理
编辑:
我发现这个链接我认为会有很大帮助!
If it is non joinable thread it will die itself and clean up
EDIT:
I found this link which I think will help a lot!