您的位置:首页 > 运维架构 > Linux

在linux下使用c++线程池threadpool

2014-02-15 19:48 537 查看


    Boost的thread库中目前并没有提供线程池,我在sorceforge上找了一个用boost编写的线程池。该线程池和boost结合的比较好,并且提供了多种任务执行策略,使用也非常简单。

 
下载地址:
    http://threadpool.sourceforge.net/
 
使用threadpool:
    这个线程池不需要编译,只要在项目中包含其头文件就可以了。
    例如我的threadpool.hpp文件路径(文件夹下有threadpool.hpp的路径)为/root/C++/app/threadpool-0_2_5-src/threadpool/boost,只需把这个目录下的所有文件(一个文件加一个目录)拷贝到你的项目中就可以使用了。
写一个简单的例子:

#include <iostream>

#include "threadpool.hpp"

using namespace std;
using boost::threadpool::pool;

// Some example tasks
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";

}

int main(int argc,char *argv[])

{

    // Create fifo thread pool container with two threads.
    pool tp(2);

    // 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();

    // Now all tasks are finished!    
    return(0);

}

    然后开始编译
    g++ test.cc -o boos -lboost_thread  // 编译时一定要加上线程库引用,否则会出现一大票编译错误哦
    一般来说编译都能通过,开始执行一下
    ./test   
    error while loading shared libraries: libboost_thread.so.1.49.0: cannot open shared object file: No such file or directory
    按字面意思是说运行时找不到 libboost_thread.so.1.49.0 这个共享类库因此也无法加载,我们知道类库默认都放在 /usr/local/lib 我们在该目录下可以找到提示无法加载的类库。
 
    这个时候我们需要执行一下这个命令

    $ sudo ldconfig /usr/local/lib
    再执行程序就OK了。
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: