QThreadPool 使用记录

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
}


// CThreadPoolEx.h

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,我也没有找到原因,有知道的可以指出。


自己开发过程中的一点积累,欢迎指正!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值