简单使用Boost线程池threadpool
生活随笔
收集整理的這篇文章主要介紹了
简单使用Boost线程池threadpool
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
場景:
1.在一些多線程的程序中,比如服務(wù)端響應(yīng)請求時,可以同時響應(yīng)多個客戶端的請求,但是響應(yīng)請求的個數(shù)(即線程)的個數(shù)過多的話就會造成系統(tǒng)資源損耗過多而宕機,還比在做一些下載的程序時,可同時開5個下載任務(wù),對應(yīng)的其實就是線程。但是最多線程是有上限的,而且每次創(chuàng)建線程和銷毀線程都會大量損耗資源和時間。所以解決辦法之一就是使用線程池控制線程個數(shù),復(fù)用創(chuàng)建過的線程。
threadpool直接使用Boost庫,不需要另外編譯Boost庫
只是開啟線程,調(diào)度線程的數(shù)量,不對單個線程進(jìn)程操作(比如暫停,恢復(fù),停止)
編譯的時候注意加上鏈接庫:
LIBS := -lboost_thread
#include <stdio.h> #include <string.h> #include <iostream> #include <boost/threadpool.hpp>using namespace std; using namespace boost::threadpool;void task_1() {cout << "task_1 start" << endl;cout << "thead_id(task_1): " << boost::this_thread::get_id() << endl;for (int i = 0; i < 10; i++){cout << "1111111111111111111111111" << endl;sleep(1);} }void task_2() {cout << "task_2 start" << endl;cout << "thead_id(task_2): " << boost::this_thread::get_id() << endl;for (int i = 0; i < 30; i++){cout << "222222222222222222222222" << endl;sleep(1);} }void DoGetVersionNoForUpdate(int a) {cout << "task_3 start" << endl;cout << "thead_id(task_3): " << boost::this_thread::get_id() << endl;for (int i = 0; i < 5; i++){cout << a*a << endl;sleep(1);} }int main(int argc, char *argv[]) {//設(shè)置允許開啟的線程數(shù)pool tp(10);//加入線程調(diào)度,可以通過指針傳參tp.schedule(&task_1);tp.schedule(&task_2);int i =10;tp.schedule(boost::bind(DoGetVersionNoForUpdate, i));//tp.wait();return (0); }
總結(jié)
以上是生活随笔為你收集整理的简单使用Boost线程池threadpool的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 查看UNIX/Linux资源占用的top
- 下一篇: apr_pool -- 内存池