Boost使用线程池

1、首先需要编译安装boost【QT】

https://www.cnblogs.com/judes/p/11027830.html

2、下载线程池源码

http://threadpool.sourceforge.net/

3、解压

4、将上面框出的文件复制到Qt目录

 

 5、配置pro

DEPENDPATH += $$PWD/Boost/lib
INCLUDEPATH += $$PWD/Boost/include/boost-1_78/
#LIBS+= $$PWD/Boost/lib/libboost_thread-mgw8-mt-d-x32-1_78.a
LIBS+= -L$$PWD/Boost/lib/ -llibboost_thread-mgw8-mt-d-x32-1_78

上面两种方式都可以

6、简单例子

#include <boost/threadpool.hpp>

void first_task()
{
    cout << "first task is running\n" ;
}

void second_task()
{
    cout << "second task is running\n" ;
}

void task_with_parameter(int value)
{
    cout << "task_with_parameter(" << value << ")\n";
}
void ExecuteWithThreadpool()
{
    //设置允许开启的线程数
    boost::threadpool::pool tp(3);


    // Add some tasks to the pool.
    tp.schedule(&first_task);
    tp.schedule(&second_task);
    tp.schedule(boost::bind(task_with_parameter, 4));

    // Wait until all tasks are finished.
    tp.wait();


    cout << "end." << endl;
}

int main(int argc, char *argv[]){
    QApplication a(argc, argv);

    ExecuteWithThreadpool();

    return a.exec();
}

 7、队列+线程池

void test1()
{
    for(int i=0;i<100;++i){
        QThread::msleep(200);
        qDebug()<<QThread::currentThreadId()<<"--->"<<i;
    }
}
void test2()
{
    for(int i=0;i<100;++i){
        QThread::msleep(200);
        qDebug()<<QThread::currentThreadId()<<"...>"<<i;
    }
}
void test3()
{
    for(int i=0;i<100;++i){
        QThread::msleep(200);
        qDebug()<<QThread::currentThreadId()<<"###>"<<i;
    }
}


typedef boost::function<void()> TaskItem;
void MainWindow::on_pushButton_3_clicked()
{
    std::queue<boost::function<void()>> q;
    q.push([](){
        for(int i=0;i<100;++i){
            QThread::msleep(100);
            qDebug()<<QThread::currentThreadId()<<"--->"<<i;
        }
    });
    q.push([](){
        for(int i=0;i<100;++i){
            QThread::msleep(100);
            qDebug()<<QThread::currentThreadId()<<"...>"<<i;
        }
    });
    q.push([](){
        for(int i=0;i<100;++i){
            QThread::msleep(100);
            qDebug()<<QThread::currentThreadId()<<"###>"<<i;
        }
    });

   TaskItem item1 = q.front();
   q.pop();
   tp.schedule(item1);

   TaskItem item2 = q.front();
   q.pop();
   tp.schedule(item2);

   TaskItem item3 = q.front();
   q.pop();
   tp.schedule(item3);
   qDebug()<<"............";
}

 上面的boost::function可以替换成std::function

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朱小勇本勇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值