【发布时间】:2017-05-31 09:15:57
【问题描述】:
我有一个读取数据的线程
class MyThread: QThread
{
...
}
void MyThread::run ()
{
uint8_t* buffer; // in my real code, it's a ring, so there is not read during write
// ...
while (true)
{
if (isInterruptionRequested())
return;
USB_READ(buffer);
emit newData(buffer);
}
}
在我的 UI 类中,我有:
connect(this, &UIClass::newData, m_thread, &MyThread::newData);
// ...
void newData(uint8_t* data)
{
// Process data
}
void UIClass::closeEvent(QCloseEvent *event)
{
disconnect(this, &UIClass::newData, m_thread, &MyThread::newData);
m_thread->requestInterruption();
m_thread->wait();
}
问题在于,当我点击“关闭”时,线程被破坏,导致指针data 无效。有时会调用信号newData,这会导致我的函数使用无效指针和段错误。如何确定这不会发生?
目前,我使用带有任意延迟的 std::this_thread::sleep_for() ,它可以工作,但我觉得这不是很漂亮
我的想法:
- 断开信号
- 等待待处理的信号被执行
- 退出
【问题讨论】:
标签: c++ multithreading qt qthread