4.QT中进程操作,线程操作

来源:互联网 发布:java http协议解析 编辑:程序博客网 时间:2024/05/22 01:51

  1. QT中的线程操作

T19Process.pro

SOURCES+=\

   main.cpp

 

CONFIG+=C++11

main.cpp

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);
 
    QProcess process;
    // process.start("/home/xuegl/T0718/build-T18Database-Desktop-Debug/T18Database");
    process.start("ssh root@42.121.13.248");
    // process.start("ssh", QStringList() << "root@42.121.13.248" << "aa" << "bbb");
    // process.write("1\n", 2);
    process.waitForFinished();
 
    // process.waitForFinished();
    qDebug() << process.readAll();
    // qDebug() << process.exitCode();
 
    return app.exec();
}
  1. 多线程(可以通过moveToThread(QThread *)的方法指定给指定的线程

新建项目T20Thread,项目代码如下:

T20Thread.pro

HEADERS+=\

   Worker.h\

   MyThread.h

 

SOURCES+=\

   Worker.cpp\

   MyThread.cpp\

   main.cpp

Worker.h

#ifndefWORKER_H

#defineWORKER_H

 

#include<QObject>

#include<QThread> //要开启线程的时候需要使用头文件<QThread>

#include<QDebug>

classWorker:publicQObject

{

   Q_OBJECT

public:

   explicitWorker(QObject*parent= 0);

 

   QThread_thread;

 

   boolevent(QEvent*ev)

   {

       //通过QThread::currentThread()可以获得当前线程信息

       qDebug()<<"event:"<<QThread::currentThread();

       returnQObject::event(ev);

   }

signals:

 

publicslots:

   voiddoWork()

   {

       qDebug()<<QThread::currentThread();

   }

};

 

#endif//WORKER_H

Worker.cpp

#include"Worker.h"

 

Worker::Worker(QObject*parent):

   QObject(parent)

{

   //this->moveToThread(&_thread);

   _thread.start();

   connect(&_thread,SIGNAL(finished()),this,SLOT(deleteLater()));

}

MyThread.h

#ifndefMYTHREAD_H

#defineMYTHREAD_H

 

#include<QThread>

#include<QDebug>

classMyThread:publicQThread

{

   Q_OBJECT

public:

   explicitMyThread(QObject*parent= 0);

 

   voidfoo()

   {

       qDebug()<<QThread::currentThread();

   }

 

   voidrun()

   {

       foo();

       qDebug()<<"threadisrun";

   }

 

signals:

 

publicslots:

 

};

 

#endif//MYTHREAD_H

MyThread.cpp

#include"mythread.h"

 

MyThread::MyThread(QObject*parent):

   QThread(parent)

{

}

main.cpp

#include<QCoreApplication>

#include"mythread.h"

#include"worker.h"

#include<QTimer>

intmain(intargc,char*argv[])

{

   QCoreApplicationapp(argc,argv);

#if0

   MyThreadthread;

   thread.start();

 

   thread.foo();

#endif

 

   qDebug()<<"mainthreadis"<<QThread::currentThread();

   Worker*worker=newWorker();

   QTimer*timer=newQTimer;

   //worker->moveToThread(&thread);

 

   QObject::connect(timer,SIGNAL(timeout()),worker, SLOT(doWork()));

   timer->setInterval(1000);

   timer->start();

 

   returnapp.exec();

}

运行结果:

 

0 0