Qt moveToThread开启线程的一种方法

本文详细介绍了在Qt中如何正确地管理线程资源,包括创建、启动、停止线程,以及如何确保线程安全地退出并释放相关资源。通过实例展示了如何使用QThread进行线程操作,并提供了在主线程与工作线程间通信的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值