1. 程式人生 > >Qt併發處理 QtConcurrent

Qt併發處理 QtConcurrent

pro檔案:

QT          += concurrent

h檔案:

#include <QMainWindow>
#include <QEvent>
#include <QtConcurrent/QtConcurrent>
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    bool event ( QEvent * event );

public slots:
    void pushbtnClickSL();


private:
    Ui::MainWindow *ui;
};



///////////////////////////////////////

void thread_add(QObject *receiver,int a,int b);

struct ProgressEvent : public QEvent

{

    enum {EventId = QEvent::User+1};

    explicit ProgressEvent(bool saved_, const QString &message_)

        : QEvent(static_cast<Type>(EventId)),

          saved(saved_), message(message_) {}

    const bool saved;

    const QString message;

};
cpp檔案:
void MainWindow::pushbtnClickSL()
{
    for(int i=0;i<99;i++)

        for(int j=0;j<99;j++)

    QtConcurrent::run(thread_add,this,i,j);
}


void thread_add(QObject *receiver,int a,int b)
{

    QString message = QString("%1 + %2 = %3   ThreadId : %4").arg(a).arg(b).arg(a + b).arg((unsigned long long)QThread::currentThreadId());
    QApplication::postEvent(receiver,new ProgressEvent(true, message));

}


bool MainWindow::event ( QEvent * event )
{

    if (event->type() == static_cast<QEvent::Type>(ProgressEvent::EventId)) {

        ProgressEvent *progressEvent = static_cast<ProgressEvent*>(event);

        Q_ASSERT(progressEvent);

        qDebug()<< progressEvent->message;

        return true;
    }
    return QMainWindow::event(event);

}

demo下載連結:

https://download.csdn.net/download/qq_27175513/10372975