1.QThread::run()
#ifndef QCTHREAD_H
#define QCTHREAD_H
#include <QThread>
class QCThread : public QThread
{
Q_OBJECT
public:
explicit QCThread(QObject *parent = 0);
protected:
void run();
signals:
public slots:
void Stop();
private:
bool m_stop;
};
#endif // QCTHREAD_H
#include "qcthread.h"
#include <QDebug>
QCThread::QCThread(QObject *parent) :
QThread(parent),
m_stop(true)
{
}
void QCThread::Stop()
{
m_stop = false;
}
void QCThread::run()
{
m_stop = true;
while (m_stop)
{
qDebug()<<"QThread::run()->"<<QThread::currentThread();
QThread::sleep(1);
}
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "qcthread.h"
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
QCThread *m_cThread;
};
#endif // WIDGET_H
#include "widget.h"
#include <QDebug>
#include <QTimer>
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
qDebug()<<"main->"<<QThread::currentThread();
m_cThread = new QCThread(this);
m_cThread->start();
}
Widget::~Widget()
{
m_cThread->Stop();
m_cThread->terminate();
m_cThread->wait();
}
2.obj.moveToThread()
#ifndef QCWORK_H
#define QCWORK_H
#include <QObject>
class QCWork : public QObject
{
Q_OBJECT
public:
explicit QCWork(QObject *parent = 0);
signals:
public slots:
void Work();
};
#endif // QCWORK_H
#include "qcwork.h"
#include <QThread>
#include <QDebug>
QCWork::QCWork(QObject *parent) :
QObject(parent)
{
}
void QCWork::Work()
{
qDebug() <<"obj.moveToThread()->"<< QThread::currentThread();
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QThread>
#include "qcwork.h"
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
QThread *m_thread;
QCWork *m_cwork;
};
#endif // WIDGET_H
#include "widget.h"
#include <QDebug>
#include <QTimer>
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
qDebug()<<"main->"<<QThread::currentThread();
m_thread = new QThread(this);
QCWork *m_cwork = new QCWork();
QTimer *time = new QTimer(this);
m_cwork->moveToThread(m_thread);
m_thread->start();
connect(time,SIGNAL(timeout()),m_cwork,SLOT(Work()));
time->start(1000);
}
Widget::~Widget()
{
m_thread->quit();
m_thread->wait();
}
3.std::thread
#include <iostream>
#include <thread>
using namespace std;
void t1()
{
for (int i = 0; i < 20; ++i)
{
cout << "t1111\n";
}
}
void t2()
{
for (int i = 0; i < 20; ++i)
{
cout << "t22222\n";
}
}
int main()
{
thread th1(t1);
thread th2(t2);
th1.join(); //等待th1执行完
th2.join(); //等待th2执行完
/*
还可以使用detach来解决,detach是用来和线程对象分离的,这样线程可以独立地执行.
不过这样由于没有thread对象指向该线程而失去了对它的控制,当对象析构时线程会继续在后台执行,但是当主程序退出时并不能保证线程能执行完。
如果没有良好的控制机制或者这种后台线程比较重要,最好不用detach而应该使用join。
*/
//th1.detach();
//th2.detach();
cout << "here is main\n\n";
return 0;
}
4.线程安全问题
多进程访问同一个变量