QThreadPool使用小例子
// QThreadPool加入的对象只能是QRunnable
// CRunObj.h
class CRunObj : public QRunnable
{
public:
CRunObj();
~CRunObj();
void setStop() { m_bStop = true; }
private:
void run();
bool m_bStop;
};
// CRunObj.cpp
CRunObj::CRunObj()
: m_bStop(false)
{
this->setAutoDelete(false);
}
void run()
{
// do something
}
class CThreadPoolEx
{
public:
CThreadPoolEx();
~CThreadPoolEx();
CRunObj* m_pRunObj;
}
// CThreadPoolEx.cpp
CThreadPoolEx::CThreadPoolEx()
{
m_pRunObj = new CRunObj;
QThreadPool::globalInstance()->start(m_pRunObj);
}
CThreadPoolEx::~CThreadPoolEx()
{
// 停止线程
m_pRunObj->setStop();
// 从线程池中移除
QThreadPool::globalInstance()->cancel(m_pRunObj);
QThreadPool::globalInstance()->waitForDone();
QThreadPool::globalInstance()->clear();
}
如果设置了setAutoDelete为true,则当run执行退出时QRunnable对象自动析构,再对线程池进行cancel、clear等操作时,可能会导致程序崩溃。
还有需要注意的是,我在Win7 64位机子上开发,线程池默认的最大线程数为4,需要根据使用场景重新设置一下。
至于为什么是4,我也没有找到原因,有知道的可以指出。
自己开发过程中的一点积累,欢迎指正!