Qt多线程:QtConcurrent配合lambda表达式(实例)

QtConcurrent类可以很简单的实现多线程编程。

实例:

功能:

在子线程中,读当前目录下的main.cpp文件,写入objectFile.cpp文件。

(下面给出QThread方法和QtConcurrent方法)

1、在.pro工程文件中加入

QT += concurrent

CONFIG += c++11

2、源代码

//main.cpp

#include 
#include 
#include 
#include 
#include "mythread.h"
#include 
#include 

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug()<<"Main: "<< a.thread()->currentThread();

    QString sourceFile = "E:/qt/QThread/main.cpp";
    QString objectFile = "E:/qt/QThread/objectFile.cpp";

    //继承QThread方式
    //{
    //    MyThread thread(sourceFile,objectFile);
    //    thread.start();
    //}

    //使用QtConcurrent
    QtConcurrent::run([&sourceFile,&objectFile]()
    {
        QFile mSrc(sourceFile);
        QFile mObj(objectFile);
        QByteArray data;
        if(mSrc.open(QFile::ReadWrite | QFile::Text))
        {
            data = mSrc.readAll();
            if(mObj.open(QFile::WriteOnly | QFile::Text))
            {
                mObj.write(data);
                mObj.close();
                mObj.waitForBytesWritten(200);
            }
            else
            {
                qDebug()<


//mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H
#include 
#include 
#include 
#include 

class MyThread : public QThread
{
public:
    MyThread(QString &src,QString &obj);

private:
    void run();

private:
    QString mSrc;
    QString mObj;

    QByteArray data;

};

#endif // MYTHREAD_H


//mythread.cpp

#include "mythread.h"
#include 

MyThread::MyThread(QString &src, QString &obj)
{
    mSrc = src;
    mObj = obj;
}

void MyThread::run()
{
    qDebug()<<"Child: "<

运行结果:

Qt多线程:QtConcurrent配合lambda表达式(实例)_第1张图片


源码下载:


你可能感兴趣的:(Qt编程)