如何在Qt中创建并行线程?

时间:2018-04-09 18:19:27

标签: c++ qt qthread

我在Qt中为经理线程创建了一个Worker类。

#include <QThread>
#include <QProcess>
#include <QObject>

class Worker_Bis : public QObject
{
    Q_OBJECT

public:
    Worker_Bis() : flag_running(false), flag_stopping(false){ 
    thread = new QThread();
    moveToThread(thread);
    connect(thread, SIGNAL(started()), this, SLOT(start()));
    connect(thread, SIGNAL(terminated()), this, SLOT(stop()));
    connect(this, SIGNAL(finished()), thread, SLOT(quit()));
    connect(this, SIGNAL(terminated()), thread, SLOT(quit()));
    connect(thread, SIGNAL(finished()), this, SLOT(deleteLater()));  

    thread->start();
}

~Worker_Bis(){  

    if (!isRunning())
        thread->deleteLater();

    flag_stopping = true;

    while (isRunning()){}

    deleteLater();
}

bool isRunning() { return flag_running; };
bool isStopping() { return flag_stopping; };
virtual int getLoops() { return 1; };

public slots:

void start(){
    flag_running = true;
    flag_stopping = false;
    starting();
    emit started();

    int exit;
    for (int loop = 0; loop < getLoops(); ++loop){
        if (isStopping()){
            exit = -1;
            break;
        }
        emit startLoop(loop);

        exit = exec(loop);

        if (exit != 0)
            break;
        emit finishLoop(loop);
    }

    finishing(exit);
    if (exit == -1)
        emit terminated();

    else{
        emit finished();

        if (exit != 0)
            emit error(exit);
    }
    flag_running = false;
  };

  void stop(){
    flag_stopping = true;
    stopping();
    emit stopped();
  };

signals:
  void started();
  void finished();
  void stopped();
  void terminated();
  void error(int code);
  void startLoop(int loop);
  void finishLoop(int loop);

protected:
  QThread* thread;
  bool flag_stopping;
  bool flag_running;
  virtual void starting() {};
  virtual int exec(int loop) { return 0; };
  virtual void finishing(int) {};
  virtual void stopping() {};
};

我实施了两个按钮:开始和停止。我启动一个线程点击开始按钮,我停止线程点击停止按钮。

void ButtonStartClicked(){
    worker = new Worker(myObj);
}

void ButtonStopClicked(){
    delete worker;
}

如果我多次点击开始按钮,我会得到并行线程。我可以多次点击开始按钮来获取一些内存问题吗?

0 个答案:

没有答案