使用boost線程池

boost threadpool庫下載鏈接https://github.com/CppPeng/threadpool,boost庫無須編譯可以直接使用

在使用過程中可能會報error C2065: 'TIME_UTC' : undeclared identifier錯誤

解決方案參考https://github.com/vpython/visual/issues/3

#include <iostream>
#include <string>
#include "boost/bind.hpp"
#include "boost/thread.hpp"
#include "boost/threadpool.hpp"
using namespace std;
using namespace boost;
const int COUNT = 10000;
void firstTask()
{
    for (int i = 0; i < COUNT; ++i) {

       // this_thread::get_id()獲取本線程的線程id
        cout << this_thread::get_id() << " " << i << endl;
    }
}

void secondTask(std::string str)
{
    for (int i = 0; i < COUNT; ++i) {
        cout << str << ":" << this_thread::get_id() << i << endl;
    }
}

int main(void)
{

   // thread::hardware_concurrency()獲取cpu個數
    int numKernel = thread::hardware_concurrency();
    cout << numKernel << endl;
    threadpool::pool tp(numKernel);
    
    tp.schedule(&firstTask);
    tp.schedule(&firstTask);
    tp.schedule(&firstTask);
    tp.schedule(boost::bind(&secondTask, std::string("second task")));

   // 等待執行完畢
    tp.wait();
    return 0;
}

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章