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

posted @ 2022-03-06 21:32  朱小勇  阅读(851)  评论(0编辑  收藏  举报