我按照本教程了解 QThreads
:http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
我遇到的唯一问题是杀死 QThread
. 我在工作对象的 process()
循环中有一个标志,我将其推入我的 QThread
实例,称为 m_ShouldSendFrames
. 如果该标志被翻转为假,则我的处理循环中断并且工作者对象发出 finished()
信号 .
我遇到的问题是我似乎无法在 QThread
中获取我的worker对象以从主线程接收我的 stopSendingFrames()
信号 . 我连接(并且连接返回'true'),如下所示:
connect(this, SIGNAL(stopSendingFrames()), m_UdpWorkerBlended, SLOT(stopFrames()),Qt::QueuedConnection); // Stop broadcasting
在我的 killUdpThread
函数中,我想发出 stopSendingFrames()
信号并让 m_UdpWorker
对象得到它 . 但它永远不会!我可以让标志改变的唯一方法是在_1400020中执行此操作:
m_UdpWorkerBlended->stopFrames();
然而,这是不安全的并且随机崩溃,因为它没有从工作人员正在运行的 QThread
调用 .
我也尝试了 invokeMethod
方式 - 但它也不会触发插槽:
QMetaObject::invokeMethod(m_UdpWorkerBlended,"stopFrames",Qt::QueuedConnection);
有人可以帮我理解为什么我不能调用 invokeMethod
或使用信号来触发我在 QThread
中的工作对象中运行的插槽但我可以直接调用它(不安全)吗?谢谢!
启动线程功能:
int UdpThreadController::startUdpThread(int frameType, int port, QString ip) {
#if SINGLETON_CAMERA_UDP_DEBUG
qDebug() << "Starting Thread! Frame type is: " << frameType;
#endif
// Check for type of frame to emit
if ( frameType == 0 ) {
#if SINGLETON_CAMERA_UDP_DEBUG
qDebug() << "Frames are vl";
#endif
// Delete any existing threads / workers
killUdpThread(0);
// New objects
m_UdpThreadBlended = new QThread();
m_UdpWorkerBlended = new UdpWorker();
// Assign Port and IP and Frame Type
m_UdpWorkerBlended->m_ShouldSendFrames = true;
m_UdpWorkerBlended->m_Port = port;
m_UdpWorkerBlended->m_AddressToUse = ip;
m_UdpWorkerBlended->m_FrameType = frameType;
// Push into thread
m_UdpWorkerBlended->moveToThread(m_UdpThreadBlended);
// Connect signals
connect(this, SIGNAL(stopSendingFrames()), m_UdpWorkerBlended, SLOT(stopFrames()),Qt::QueuedConnection); // Stop broadcasting
connect(m_UdpThreadBlended, SIGNAL(started()), m_UdpWorkerBlended, SLOT(process()));
connect(m_UdpWorkerBlended, SIGNAL(finished()), m_UdpThreadBlended, SLOT(quit()));
connect(m_UdpWorkerBlended, SIGNAL(finished()), m_UdpWorkerBlended, SLOT(deleteLater()));
connect(m_UdpThreadBlended, SIGNAL(finished()), m_UdpThreadBlended, SLOT(deleteLater()));
m_UdpThreadBlended->start();
// All done
return 0;
杀线程功能:
int UdpThreadController::killUdpThread(int frameType) {
#if SINGLETON_CAMERA_UDP_DEBUG
qDebug() << "Killing Thread! Frame type is: " << frameType;
#endif
// Check for type of frame to emit
if ( frameType == 0 ) {
// Delete any existing threads / workers
if ( m_UdpWorkerBlended ) {
#if SINGLETON_CAMERA_UDP_DEBUG
qDebug() << "Emit signal to kill thread...";
#endif
// Stop broadcasting
m_UdpWorkerBlended->stopFrames();
}
#if SINGLETON_CAMERA_UDP_DEBUG
qDebug() << "Success ending UDP...";
#endif
// All done
return 0;
}
1 回答
感谢您的投入 . 我通过一个单例来解决它,它有一个标志,QThread中我的worker对象中的处理循环读取每个循环迭代 . 它受QReadWrite锁保护 .