.h
#ifndef MULTHREAD_H
#define MULTHREAD_H
#include"qobject.h"
#include "qthread.h"
using namespace std;
class Thread : public QThread
{
Q_OBJECT
public:
Thread();
~Thread();
/**
* @brief setFunc 设置匿名函数
* @param func 匿名函数
*/
void setFunc(function<void()>func);
void quitThread();
private:
void run();
private:
function<void()>m_func;
};
class MulThread : public QObject
{
Q_OBJECT
public:
MulThread();
~MulThread();
/**
* @brief run 开启一个线程运行一个匿名函数并加入线程池
* @param func 匿名函数
* @return int 返回线程的id (当前线程池开启的线程的id)
*/
int run(function<void()>func);
void quitAllThread();
void quitThread(int threadId);
signals:
void signal_finshed(int threadId);
private:
QMap<int,Thread*> m_thredPool;
int m_id = 0;
};
#endif // MULTHREAD_H
.cpp
#include "MulThread.h"
Thread::Thread()
{
}
Thread::~Thread()
{
quitThread();
}
void Thread::run()
{
m_func();
}
void Thread::setFunc(function<void()>func)
{
m_func = func;
}
void Thread::quitThread()
{
quit();
wait();
}
MulThread::MulThread()
{
}
MulThread::~MulThread()
{
quitAllThread();
}
int MulThread::run(function<void()>func)
{
Thread* thread = new Thread;
thread->setFunc(func);
int id = m_id;
QObject::connect(thread,&Thread::finished,this,[=](){
quitThread(id);
emit signal_finshed(id);
});
m_thredPool.insert(id,thread);
thread->start();
m_id++;
return id;
}
void MulThread::quitAllThread()
{
qDeleteAll(m_thredPool);
m_thredPool.clear();
}
void MulThread::quitThread(int threadId)
{
delete m_thredPool[threadId];
m_thredPool.remove(threadId);
}
使用:
void MainWindow::test()
{
threadPool = new MulThread;
connect(threadPool,&MulThread::signal_finshed,[=](int id){
qDebug()<<"threadId:"<<id<<endl;
});
threadPool->run([=](){
for(int i = 0;i<100;i++)
{
qDebug()<<"haha"<<endl;
}
});
threadPool->run([=](){
for(int i = 0;i<50;i++)
{
qDebug()<<"zzzzzz"<<endl;
}
});
threadPool->run([=](){
for(int i = 0;i<50;i++)
{
qDebug()<<"0000"<<endl;
}
});
threadPool->run([=](){
for(int i = 0;i<10000;i++)
{
qDebug()<<"pppppp"<<endl;
}
});
}