我在程序中删除QUdpSocket时遇到问题。问题是:我在一个线程中创建UdpSocket,然后在另一个线程中删除它。为了简化我的代码,我有这个:
class SocketHandler : public QObject
{
Q_OBJECT
public:
SocketHandler():
socket(this)
{
socket.bind(8888);
}
~SocketHandler();
private:
QUdpSocket socket;
};
class ThreadStorage
{
public:
ThreadStorage():
handler(new SocketHandler()),
thread(new QThread())
{
handler->moveToThread(thread);
}
~ThreadStorage();
private:
SocketHandler* handler;
QThread* thread;
};
class Killer : public QObject
{
Q_OBJECT
public:
Killer(ThreadStorage* stor):
storage(stor)
{
}
private:
ThreadStorage* storage;
public slots:
void kill()
{
delete storage;
}
};
然后我将插槽连接到MainWindow
中的按钮:
void MainWindow::onButton()
{
ThreadStorage* storage = new ThreadStorage();
QTimer* timer = new QTimer();
timer->setInterval(2000);
timer->setSingleShot(true);
Killer* killer = new Killer( storage);
connect(timer, SIGNAL(timeout()), killer, SLOT(kill()));
QThread* thread = new QThread();
connect(thread, SIGNAL(started()), timer, SLOT(start()));
timer->moveToThread(thread);
killer->moveToThread(thread);
thread->start();
}
删除套接字时我有错误:
QCoreApplication :: sendEvent中的ASSERT失败:“无法将事件发送到不同线程拥有的对象。当前线程7287a0。接收器''(类型'QNativeSocketEngine')是在线程709838中创建的”,文件内核\ qcoreapplication.cpp ,第521行
我正在使用带有msvc2013 + opengl的QT 我理解这个特定代码中的内存泄漏和其他愚蠢错误。此代码仅供您查看我的大型程序中发生的情况。它只是最小,完整和可验证的例子 那么,如何在多线程应用程序中正确管理UdpSocket?感谢。