Qt5 多线程简单实现 以及传参

1.run模式更适合于多开

 //.cpp
#pragma once
#include <QThread>
class SimpleThreadOne : public QThread //继承Thread
{
public:
	int para1;
	QString para2;
    SimpleThreadOne(int input1,QString input2):para1(input1),para2(input2)//传参
	{
	};
     void run();
};

 //.h
#include "simplethreadone.h"
void SimpleThreadOne::run()
{
    while (true)
    {
        sleep(1000);//费时主程序
    }
}

//main
#include "mainwindow.h"
#include <QApplication>
#include "simplethreadone.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
 	QString a="fast";
 	int b=1;
 	//开一百个子线程
 	for(int i=0;i<100;i++)
 	{
    	SimpleThreadOne *SThread = new SimpleThreadOne(b,a);
    	SThread->start();
 	}
    return a.exec();
}

2.movetoThread Qt推荐 更安全

//.h
#pragma once
#include <QObject>
class SimpleThreadTwo : public QObject//继承QObject
{
    Q_OBJECT
public:
    explicit SimpleThreadTwo(QObject *parent = nullptr);
 
public slots:
    void doSomething(QString para1,int para2);
};

//.cpp
#include "simplethreadtwo.h"
#include <unistd.h>
SimpleThreadTwo::SimpleThreadTwo(QObject *parent) : QObject(parent)
{}
void SimpleThreadTwo::doSomething(QString para1,int para2)
{
        sleep(2);
}

//MainWindows.h
#pragma once
#include <QMainWindow>
#include "simplethreadtwo.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void SendStart(void);
signals:
    void Signal1(QString input1,int input2);
private:
    Ui::MainWindow *ui;
};

//MainWindows.cpp
 #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QThread* m_objThread=new QThread();;
    SimpleThreadTwo* m_ThreadTwo = new SimpleThreadTwo();//new 多线程对象
    m_ThreadTwo->moveToThread(m_objThread);//movetoThread
    connect(m_objThread,&QThread::finished,m_objThread,&QObject::deleteLater);//停止后删除
    connect(this,&MainWindow::Signal1,m_ThreadTwo,&SimpleThreadTwo::doSomething);//参数要对应 最多五个
    m_objThread->start();//一定记得start

	//开始执行
    QString a="XX";
    int b=1;
     emit Signal1(a,b); 
}
MainWindow::~MainWindow()
{
    delete ui;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值