boost之第三方线程池
简介
其是模板类,支持future,下载地址为threadpool,基实现是基于pimpl即pool_core_type
结构
SchedulingPolicy调度策略有:fifo_scheduler
,lifo_scheduler
,prio_scheduler
SchedulingPolicy关闭策略有:wait_for_all_tasks
,wait_for_active_tasks
,immediately
SizePolicyController线程池大小控制器策略有:empty_controller
,resize_controller
SizePolicy大小策略有: static_size
task适配器类型有:prio_task_func
,looped_task_func
和支持future的future_impl_task_func
支持future
schedule
:首先创建future_impl,然后根据future_impl创建future和future_impl_task_func,同时返回future
template<class Pool, class Function>
typename disable_if < is_void< typename result_of< Function() >::type >,future< typename result_of< Function() >::type >
>::type
schedule(Pool& pool, const Function& task)
{typedef typename result_of< Function() >::type future_result_type;// create future impl and futureshared_ptr<detail::future_impl<future_result_type> > impl(new detail::future_impl<future_result_type>);future <future_result_type> res(impl);// schedule future implpool.schedule(detail::future_impl_task_func<detail::future_impl, Function>(task, impl));// return futurereturn res;
}
线程池适配器
有两类函数模板,其中的一个是对象要求有run方法,另外一个就是要求是pool中的task类型
template<typename Pool, typename Runnable>bool schedule(Pool& pool, shared_ptr<Runnable> const & obj){ return pool->schedule(bind(&Runnable::run, obj));} template<typename Pool>typename enable_if < is_void< typename result_of< typename Pool::task_type() >::type >,bool>::typeschedule(Pool& pool, typename Pool::task_type const & task){ return pool.schedule(task);} template<typename Pool>typename enable_if < is_void< typename result_of< typename Pool::task_type() >::type >,bool>::typeschedule(shared_ptr<Pool> const pool, typename Pool::task_type const & task){ return pool->schedule(task);}
工作线程worker_thread
create_and_attach
:静态方法,用于创建worker_thread
static void create_and_attach(shared_ptr<pool_type> const & pool){shared_ptr<worker_thread> worker(new worker_thread(pool));if(worker){worker->m_thread.reset(new boost::thread(bind(&worker_thread::run, worker)));}}
run
:工作线程的执行体
void run()
{ scope_guard notify_exception(bind(&worker_thread::died_unexpectedly, this));while(m_pool->execute_task()) {}notify_exception.disable();m_pool->worker_destructed(this->shared_from_this());
}
当在执行execute_task
异常退出时会执行notify_exception
即died_unexpectedly
scope_guard
用于在工作线程异常退出时执行退出对应的操作
在析构时,执行m_function
~scope_guard()
{if(m_is_active && m_function){m_function();}
}
locking_ptr
对指针对象的安全操作,主要用于future_impl的线程安全操作
构造函数中上锁,析构函数中解锁
locking_ptr(volatile T& obj, const volatile Mutex& mtx): m_obj(const_cast<T*>(&obj)), m_mutex(*const_cast<Mutex*>(&mtx)){ // Lock mutexm_mutex.lock();}/// Destructor.~locking_ptr(){ // Unlock mutexm_mutex.unlock();}
operator*
获取指针所指的对象,operator->
获取对象指针
T& operator*() const{ return *m_obj; }/*! Returns a pointer to the stored instance.* \return The instance's pointer.*/T* operator->() const{ return m_obj; }