boost thread_group 的使用

boost库提供thread_group用于管理一组线程,就像是一个线程池,它内部使用std::list

#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>

using namespace std ;

boost::mutex iomutex ;
void runchild(const int n)
{
    {
        boost::mutex::scoped_lock lock(iomutex) ;
        cout<<"我是第"<<n<<"个子线程"<<endl ;
    }

    {
        boost::mutex::scoped_lock lock(iomutex) ;
        cout<<"进程"<<n<<" 退出 "<<endl ;
    }
}

void dummy(int n)
{
    boost::mutex::scoped_lock lock(iomutex) ;
    for (int i = 0 ; i < n ; ++i)
    {
        cout<<i<<"\t" ;
    }

    cout<<endl ;
}

int main()
{
    boost::thread_group group ;
    for (int num = 0 ; num < 10 ; ++num)
    {
    //create_thread()是一个工厂函数,可以创建thead对象并运行线程,同时加入内部的list
//      group.create_thread(boost::bind(&runchild , num)) ;
        group.create_thread(boost::bind(dummy , num)) ;
    }
    group.join_all() ; //等待所有线程执行结束
    system("pause") ;
    return 1 ;
}

运行结果;
这里写图片描述
thread_group内部使用shared_mutex来保护线程list,所以它本身是线程安全的,在多线程环境里可以放心使用。

转自:http://blog.csdn.net/hanshuobest/article/details/53984660

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值