使用线程编程
Programming with threads
我每次都收到消息:QObject::moveToThread: Cannot move objects with a parent
主窗口.cpp:
QTimer *timer_ = new QTimer(this);
Device* device = new Device(this);
QThread* thread = new QThread(this);
device->moveToThread(thread);
connect(timer_, SIGNAL(timeout()), device, SLOT(checkConnection()));
connect(device, SIGNAL(checkCompleted()), this, SLOT(doSomethingWhenItIsDone()));
timer_->start(3000);
设备.cpp:
Device::Device(QObject *parent) :
QObject(parent)
{
}
void Device::checkConnection() {
qDebug() << "checkConnection:" << QThread::currentThreadId();
//do something
emit checkCompleted();
}
设备构造函数中的this
意味着设备有一个父级,并且在您的情况下,该父级存在于主 GUI 线程中,因此 Qt 告诉您不能移动到另一个具有父级的线程对象。所以尝试使用下一步:
QTimer *timer_ = new QTimer(this);
Device* device = new Device;//no parent
QThread* thread = new QThread(this);
此外,您应该从以下方面开始您的线程:
thread->start();
您还需要删除您的对象,因为它没有父对象,现在是您的责任。最常见的方法是使用一些信号来指示工人已经完成了所有需要的工作。例如:
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
相关文章:
- 多线程套接字编程服务器仅从 1 个客户端线程获取消息
- OpenMP 并行编程基于线程数与执行时间的关系
- 多线程合并排序编程
- 卷曲轻松执行使用多个线程C++编程
- 带有多个线程的锁在C 中并行编程
- vmware中的线程编程,'process scheduling'没有发生
- MFC 编程:编译时出错:线程代码中的错误
- 线程编程中的堆栈组织
- 是否可以以编程方式冻结 Windows 上的线程
- 以编程方式获取与 htop 的相应 pid 匹配的进程的线程 ID
- 线程安全编程
- 我应该在多线程编程中始终锁定全局数据吗?为什么
- C++游戏、线程和并发编程
- 如何以编程方式从工作线程获得父线程和兄弟线程的CPU利用率
- 内存的多线程编程
- 我正在学习c++服务器编程,但线程不工作
- 以编程方式获取Windows上硬件线程数的可靠方法
- C++/QT中的线程化多核平台独立编程
- 访问冲突读取位置0xfeeefef2多线程编程c++窗口
- 什么是无锁多线程编程