第一种创建线程的方法:di
#include <QCoreApplication>
#include<QThread>
#include<QDebug>
#include<QMutex>
QMutex mtx;
int num = 200;
int sale = 0;
class myThreads:public QThread{
public:
void run() override{
//qDebug()<<"currentThreadId:"<<this->currentThreadId();
while (sale<num) {
mtx.lock();
if(sale<num){
sale ++;
qDebug()<<"currentThreadId:"<<this->currentThreadId()<<" sale:"<<sale;
}
mtx.unlock();
}
this->quit();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//创建4个线程
myThreads t1;
myThreads t2;
myThreads t3;
myThreads t4;
t1.start();
t2.start();
t3.start();
t4.start();
return a.exec();
}
第二种创建线程的方法:
#include <QCoreApplication>
#include<QThread>
#include<QDebug>
#include<QMutex>
#include<QRunnable>
#include<QThreadPool>
QMutex mtx;
int num = 200;
int sale = 0;
class myThreads:public QThread{
public:
void run() override{
//qDebug()<<"currentThreadId:"<<this->currentThreadId();
while (sale<num) {
mtx.lock();
if(sale<num){
sale ++;
qDebug()<<"currentThreadId:"<<this->currentThreadId()<<" sale:"<<sale;
}
mtx.unlock();
}
this->quit();
}
};
class myThread2:public QRunnable{
public:
void run(){
qDebug()<<"currentThreadId = "<<QThread::currentThreadId();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//创建4个线程
//myThreads t1;
//myThreads t2;
//myThreads t3;
//myThreads t4;
//t1.start();
//t2.start();
//t3.start();
//t4.start();
myThread2 *t5 = new myThread2();
QThreadPool::globalInstance()->start(t5);
return a.exec();
}
缺点:这种继承于QRunnable创建多线程的方式,不能使用信号和槽机制;
优点:线程池自动管理对象;
第三种创建多线程的方式:
派生于QObject,使用moveToObject方法;
第四种创建多线程的方式:
#include <QCoreApplication>
#include<QMutex>
#include<QtConcurrent>
#include<QDebug>
int tickes =100;
QMutex mtx;
void process_1(){
while(tickes>=0){
mtx.lock();
if(tickes>=0){
QThread::msleep(100);
qDebug()<<"process_1 is getting "<<tickes;
tickes--;
}
mtx.unlock();
}
}
void process_2(){
while(tickes>=0){
mtx.lock();
if(tickes>=0){
QThread::msleep(100);
qDebug()<<"process_2 is getting "<<tickes;
tickes--;
}
mtx.unlock();
}
}
void process_3(){
while(tickes>=0){
mtx.lock();
if(tickes>=0){
QThread::msleep(100);
qDebug()<<"process_3 is getting "<<tickes;
tickes--;
}
mtx.unlock();
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QtConcurrent::run(process_1);
QtConcurrent::run(process_2);
QtConcurrent::run(process_3);
return a.exec();
}