boost::thread编程-线程组

本文介绍了一个基于Boost.Thread库的线程组管理类thread_group,该类提供了创建、加入、移除线程以及对线程组内所有线程进行等待和中断的操作。通过示例代码展示了如何使用thread_group来管理多个线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.youkuaiyun.com/anda0109/article/details/41944927

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

class thread_group::private noncopyable  
{  
public:  
    template<typename F>;  
    thread* create_thread(F threadfunc);  
    void add_thread(thread* thrd);  
    void remove_thread(thread* thrd);  
    void join_all();  
    void interrupt_all();  
    int size() const;  
};  

成员函数create_thread是一个工厂函数,可以创建thread对象并运行线程,同时加入到内部的list。我们也可以在thread_group对象外部创建线程,然后使用add_thread加入线程组。
如果不需要某个线程,可以使用remove_thread删除线程组里的thread对象。
join_all()、interrupt_all()用来对list里的所有线程对象进行操作,等待或中断这些线程。

#include "stdafx.h"  
#include <iostream>  
#include <boost/thread.hpp>  
#include <boost/atomic.hpp>  

boost::mutex io_mu;//io流操作锁  

void printing(boost::atomic_int &x,const std::string &str)  
{  
    for(int i=0;i<5;++i)  
    {  
        boost::mutex::scoped_lock lock(io_mu);//锁定io流操作  
        std::cout<<str<<++x<<std::endl;  
    }  
}  

int _tmain(int argc, _TCHAR* argv[])  
{  
    boost::atomic_int x(0);  

    boost::thread_group tg;  
    tg.create_thread(boost::bind(printing,ref(x),"hello"));  
    tg.create_thread(boost::bind(printing,ref(x),"hi"));  
    tg.create_thread(boost::bind(printing,ref(x),"boost"));  
    tg.join_all();  
    getchar();  
    return 0;  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值