thread庫提供thread_group類用于管理一組線程,就像一個線程池,它內部使用std::list<thread*>來容納thread對象,類摘要如下:
~~~
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;
}
~~~