有關 QThread 多次執行程式



  • Hello

    想請問一下,有關使用QThread 重覆執行同一個代碼。
    簡單的程式如下:

    //------------------------------------work.h-------------------------------------------

    class work : public QObject
    {
        Q_OBJECT
    public:
        explicit work(QObject *parent = nullptr);
        void setinitialvalue(int value);
    
    signals:
        void finish();
        void sentresult(int);
    public slots:
    
        void dosomething();
    
    private:
        int result;
    };
    

    //-----------------------work.cpp---------------------------------

    work::work(QObject *parent) : QObject(parent)
    {
        result = 0;
    }
    
    
    void work::dosomething()
    {
    
        for(int k = 0; k < 10; k++)
            ++result;
    
        emit sentresult(result);
        emit finish();
    }
    
    void work::setinitialvalue(int value)
    {
        result = value;
    }
    
    

    //-----------------------------------mainwindows.h-----------------------

    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private slots:
        void getreault(int data);
        void GoStart();
    
    private:
        Ui::MainWindow *ui;
        QThread *thread;
        work *dowork;
        int initialvalue;
    };
    
    

    //------------------------------------mainwindows.cpp---------------------

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        initialvalue = 0;
    
        thread = new QThread();
        dowork = new work();
    
        dowork->moveToThread(thread);
        connect(thread, SIGNAL(started()), dowork, SLOT(dosomething()));
        connect(dowork, SIGNAL(finish()), thread, SLOT(deleteLater()));
        connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
        connect(dowork, SIGNAL(sentresult(int)), this, SLOT(getreault(int)));
    
        connect(ui->go_pb, SIGNAL(clicked(bool)), this, SLOT(GoStart()));
    }
    
    MainWindow::~MainWindow()
    {
        delete thread;
        delete dowork;
        delete ui;
    }
    
    
    void MainWindow::getreault(int data)
    {
        qDebug() << data;
    }
    
    void MainWindow::GoStart()
    {
        ++initialvalue;
        dowork->setinitialvalue(initialvalue);
        thread->start();
    }
    

    我按了第一次按鈕,程式會執行,但是無法再進行第二次的執行。
    請問有什麼方法以QThread多次執行,但不是同時。

    謝謝!



  • @LeonSu said in 有關 QThread 多次執行程式:

    connect(dowork, SIGNAL(finish()), thread, SLOT(deleteLater()));

    Hi~
    其实本可以多次点击start,多次执行,但是问题在于dosomething()中的发出的finish信号触发了thread.deleteLater(),导致thread销毁. 即
    connect(dowork, SIGNAL(finish()), thread, SLOT(deleteLater()));
    建议在MainWindow关闭时,再释放thread.

    另一种方法则是在点击开始时,再创建一个thread,并重新链接信号与槽.

    以上,希望能帮助到您 :D


Log in to reply