我做了一个工作线程任务,另一个是我的公共第三方功能。 我想同时运行线程插槽(例如:StartWork())和我的公共函数(例如:on_pushButton_4_clicked()),但它们不会。请告诉我如何做到这一点。这是我的代码:
Mythread.cpp
#include "mythread.h"
#include "ui_mythread.h"
Mythread::Mythread(QWidget *parent) :
QWidget(parent),
ui(new Ui::Mythread)
{
ui->setupUi(this);
//Debug
this->dumpObjectInfo();
//myWorker->dumpObjectInfo();
}
Mythread::~Mythread()
{
myWorker->abort();
WorkerThread->wait();
qDebug()<<"Deleting thread and worker in Thread "<<this->QObject::thread()->currentThreadId();
delete WorkerThread;
delete myWorker;
delete ui;
}
void Mythread::on_pushButton_2_clicked()
{
qDebug() << "stopwork signal emmitted";
emit stopWorkSignal();
}
void Mythread::on_pushButton_4_clicked()
{
myWorker = new worker;
WorkerThread = new QThread;
myWorker->moveToThread(WorkerThread);
WorkerThread->start();
connect(myWorker, SIGNAL(valueChanged(QString)),this, SLOT(myfunc(QString)));
connect(WorkerThread, SIGNAL(started()), myWorker, SLOT(StartWork()));
connect(this, SIGNAL(stopWorkSignal()), myWorker, SLOT(abort()));
qDebug()<<"inside work";
int i =0;
while (i<1000)
{
qDebug()<<":count *i=========>"<<i;
i++;
}
return;
}
void Mythread::myfunc(QString s)
{
qDebug()<<"thread TXT"<<s;
//
ui->label->setText(s);
}
worker.cpp
#include "worker.h"
#include<QDebug>
#include<mythread.h>
worker::worker(QObject *parent) :
QObject(parent)
{
_working =false;
_abort = false;
}
void worker::do_Work()
{
qDebug() << "inside do Work";
qDebug()<<"Starting worker process in Thread "<<thread()->currentThreadId();
for (int i = 1; i<100; i ++) {
// Checks if the process should be aborted
mutex.lock();
bool abort = _abort;
mutex.unlock();
if (abort) {
qDebug()<<"Aborting worker process in Thread "<<thread()->currentThreadId();
break;
}
// This will stupidly wait 1 sec doing nothing...
QEventLoop loop;
loop.processEvents(QEventLoop::AllEvents);
QTimer::singleShot(100, &loop, SLOT(quit()));
loop.exec();
//Once we're done waiting, value is updated
emit valueChanged(QString("%1").arg(i++));
}
mutex.lock();
_working = false;
mutex.unlock();
qDebug()<<"Worker process finished in Thread "<<thread()->currentThreadId();
emit finished();
}
void worker::abort()
{
qDebug()<<"Stop Thread";
mutex.lock();
if (_working) {
_abort = true;
qDebug()<<"Request worker aborting in Thread "<<thread()->currentThreadId();
}
mutex.unlock();
emit finished();
//lbl->close();
//lbl->deleteLater();
}
void worker::StartWork()
{
qDebug() << "inside StartWork";
_working = true;
_abort = false;
//emit running();
do_Work();
}
输出如下:
:count *i=========> 988
:count *i=========> 989
:count *i=========> 990
:count *i=========> 991
:count *i=========> 992
thread TXT "1"
thread TXT "3"
thread TXT "5"
thread TXT "7"
答案 0 :(得分:0)
一些问题:
你总是可以调用QThread :: currentThread()来查看它是否在正确的线程上运行,它也是操作系统的UP来安排你的线程所以期望看到两个线程的输出不可能同时发生你想要的方式。