如何在不创建线程的情况下保持后台代码运行?

时间:2019-03-15 03:56:52

标签: c++ multithreading qt pthreads

  1. 我正在尝试使用qt Creator创建一个简单的UI。后台代码会一直打印一个int标记,当用户单击按钮时,该标记会更改,因此输出也会更改。

UI如下:

enter image description here

这样的输出:单击《输出1》,然后将0更改为1

enter image description here

  1. 如何在不使用qt创建器创建线程的情况下保持后台代码运行?

这是cpp代码,我没有添加.h文件: 所有文件都可以在这里jump to all code in github

main.cpp:

    #include "MainWindow.h"
    #include <QApplication>
    #include <iostream>
    #include "deal.h"

    int main(int argc, char *argv[])
    {
      std::cout << argc << " " << argv[0] << std::endl;
    //  getchar();
      QApplication a(argc, argv);

      MainWindow w;
      w.show();


    //  getchar();
      pthread_t tid;   //Not want to create a thread to run this
      pthread_create(&tid, NULL, run, NULL); 
      //pthread_exit(&tid);
      a.exec();
      return 0;
    }

MainWindow.cpp

    #include "MainWindow.h"
    #include "ui_MainWindow.h"
    #include "deal.h"

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
      ui->setupUi(this);
      connect(ui->pbOriginSound, SIGNAL(clicked()), this, SLOT(change2_origin_sound()));
      connect(ui->pbVecSound, SIGNAL(clicked()), this, SLOT(change2_vec_sound()));
      connect(ui->pbVecNrSound, SIGNAL(clicked()), this, SLOT(change2_vec_nr_sound()));
    }

    void MainWindow::change2_origin_sound(){
      iFlag = 0;
      printf("%d", iFlag);
    }

    void MainWindow::change2_vec_sound(){
      iFlag = 1;
      printf("%d", iFlag);
    }

    void MainWindow::change2_vec_nr_sound(){
      iFlag = 2;
      printf("%d", iFlag);
    }

    MainWindow::~MainWindow()
    {
      delete ui;
    }

deal.cpp

    #include "deal.h"
    #include <iostream>
    #include <unistd.h>

    int iFlag;

    void *run(void *arg){

      while(1){
    //        sleep(1);
        printf("%d\n", iFlag);
        printf("%d%d\n", iFlag, iFlag);
      }
    }

1 个答案:

答案 0 :(得分:0)

一种常见的方法是创建一个插槽方法和一个QTimer,它将每隔几毫秒调用一次该方法,例如

在MainWindow.h中:

#include <QTimer>
#include <QMainWindow>

class MainWindow : public QMainWindow 
{
Q_OBJECT

   [...]

private slots:
   void MySlot();

private:
   QTimer myTimer;
};

在MainWindow.cpp中:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    [...]

    connect(&myTimer, SIGNAL(timeout()), this, SLOT(MySlot()));
    myTimer.start(100);   // MySlot() will be called every 100mS
}

void MainWindow::MySlot()
{
    printf("%d\n", iFlag);
}

请注意,此方法假定MySlot()将很快返回;如果不是,则MySlot()仍在GUI线程中运行,因此将冻结直到其返回为止的GUI,因此将推迟其他GUI事件的处理。因此,请确保不要在MySlot()内部做任何耗时的操作,除非您愿意使用响应速度不太快的GUI。