Qt moveToThread开启线程的一种方法

 如何正常的退出,释放线程和线程槽

Worker不能设置parent

A *a = new A;
QThread *t = new QThread;
a->moveToThread(t);
connect(t, SIGNAL(started()), a, SLOT(start()));
connect(a, SIGNAL(finish()), a, SLOT(deleteLater()));
connect(a, SIGNAL(destroyed()), t, SLOT(quit()));
connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
#ifndef MYMOVETOTHREAD_H
#define MYMOVETOTHREAD_H
#include <QObject>
#include <QThread>
#include <QDebug>

class Worker:public QObject
{
    Q_OBJECT
public:
    Worker(){}
    ~Worker(){}
public slots:
    void first()
    {
        qDebug()<<QThread::currentThreadId();
    }
    void second()
    {
        qDebug()<<QThread::currentThreadId();
    }
    void three()
    {
        qDebug()<<QThread::currentThreadId();
    }
};



#endif // MYMOVETOTHREAD_H

 

#include <QDateTime>
#include <QDebug>
#include <QThread>
#include <QDir>
#include "mymovetothread.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QString strTemp = QDir::tempPath();
    qDebug()<<strTemp;
    myWork = new Worker;

    connect(ui->firstButton,SIGNAL(clicked(bool)),myWork,SLOT(first()),Qt::QueuedConnection);
    connect(ui->secondButton,SIGNAL(clicked(bool)),myWork,SLOT(second()),Qt::QueuedConnection);
    connect(ui->threeButton,SIGNAL(clicked(bool)),myWork,SLOT(three()),Qt::QueuedConnection);

    QThread* thread = new QThread;
    myWork->moveToThread(thread);
    thread->start();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_startButton_clicked()
{
    if(!thread.isRunning())
    {
        qDebug()<<"thread is not running";
    }
    thread.start();
    ui->stopButton->setEnabled(true);
    ui->startButton->setEnabled(false);
}


void MainWindow::on_stopButton_clicked()
{
    if(thread.isRunning())
    {
        qDebug()<<"thread is running";
        thread.stop();
        ui->stopButton->setEnabled(false);
        ui->startButton->setEnabled(true);
    }
}



void MainWindow::on_selfButton_clicked()
{
    qDebug() << QThread::currentThreadId();

}

void MainWindow::on_exitButton_clicked()
{
    close();
}

 

Qt中的QThread类提供了一种在多线程应用程序中管理线程方法。然而,在使用Qt的moveToThread()方法将一个QObject派生类对象移动到另一个线程时,并不能直接暂停该线程。 moveToThread()方法实际上是将一个QObject对象的所有方法从一个线程中转移到另一个线程中执行。这样做的目的是为了在多线程应用程序中实现对象的跨线程调用,以避免线程间的竞争条件和死锁等问题。 如果需要暂停线程,可以通过其他方式来实现。例如,可以在QObject对象的方法中添加一个标志位,用来控制方法的执行。当需要暂停线程时,可以将该标志位设置为一个特定的值,使方法在执行前检查该标志位,如果值为暂停状态,就不执行。当需要恢复线程时,可以将该标志位设置为另一个值,使方法可以正常执行。 另外,也可以通过使用信号和槽机制来实现线程的暂停和恢复。可以定义一个信号暂停线程,然后在槽函数中执行暂停操作;定义另一个信号恢复线程,然后在槽函数中执行恢复操作。通过发出这两个信号,可以控制线程在暂停和恢复之间切换。 需要注意的是,在进行线程暂停和恢复的操作时,要确保线程的同步和安全。可以使用互斥锁或其他线程同步机制来保证多线程操作的正确性和可靠性。 综上所述,Qt的moveToThread()方法并不能直接用于暂停线程。但可以通过其他方式,如标志位或信号和槽机制,来实现线程的暂停和恢复操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值