boost线程池简单示例

来源:互联网 发布:ubuntu开机只进入grub 编辑:程序博客网 时间:2024/04/29 08:49

threadPool.cpp:

#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
using namespace boost;
using namespace std;

void runChild(const int n)
{
    cout << "我是第" << n << "个子线程" << endl;
    sleep(1);
    cout << "进程" << n <<  "退出" << endl;
}

int main(int argc, char** argv)
{
    int num;
    thread_group threads;

    if (argc < 2)
    {
        cout << "请提供一个要生成线程数的参数" << endl;
        exit(-1);
    }

    num = atoi(argv[1]);

    cout << "我是主程序,我准备产生" << num << "个子线程" << endl;
    for(int i = 0; i < num; i++)
    {
        threads.create_thread(bind(&runChild, i));
    }
 
    cout << "我是主程序,我在等子线程运行结束" << endl;
    threads.join_all();
    return 0;
}

 

编译:

g++ threadPool.cpp -static  -I/home/hhc/downloads/boost_1_51_0 -L/home/hhc/downloads/boost_1_51_0/bin.v2/libs/thread/build/gcc-4.5.2/release/link-static/threading-multi/ -L/home/hhc/downloads/boost_1_51_0/bin.v2/libs/system/build/gcc-4.5.2/release/link-static/threading-multi/ -lboost_system -lboost_thread -lpthread