qt thread with movetothread(带有 movetothread 的 qt 线程)
问题描述
我正在尝试使用线程创建程序:主要以一个循环开始.当测试返回 true 时,我创建一个对象,并希望该对象在另一个线程中工作然后返回并开始测试.
I'm trying to create a program using threads: the main start with a loop. When a test returns true, I create an object and I want that object to work in an other thread then return and start the test .
QCoreApplication a(argc, argv);
while(true){
Cmd cmd;
cmd =db->select(cmd);
if(cmd.isNull()){
sleep(2);
continue ;
}
QThread *thread = new QThread( );
process *class= new process ();
class->moveToThread(thread);
thread->start();
qDebug() << " msg"; // this doesn't run until class finish it's work
}
return a.exec();
问题是当我启动新线程时,主线程停止并等待新线程完成.
the problem is when i start the new thread the main thread stops and wait for the new thread's finish .
推荐答案
规范的 Qt 方式如下所示:
The canonical Qt way would look like this:
QThread* thread = new QThread( );
Task* task = new Task();
// move the task object to the thread BEFORE connecting any signal/slots
task->moveToThread(thread);
connect(thread, SIGNAL(started()), task, SLOT(doWork()));
connect(task, SIGNAL(workFinished()), thread, SLOT(quit()));
// automatically delete thread and task object when work is done:
connect(task, SIGNAL(workFinished()), task, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
如果您不熟悉信号/插槽,Task 类将如下所示:
in case you arent familiar with signals/slots, the Task class would look something like this:
class Task : public QObject
{
Q_OBJECT
public:
Task();
~Task();
public slots:
// doWork must emit workFinished when it is done.
void doWork();
signals:
void workFinished();
};
这篇关于带有 movetothread 的 qt 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有 movetothread 的 qt 线程
- GDB 不显示函数名 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 将函数的返回值分配给引用 C++? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01