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


    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了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM