【发布时间】:2014-11-13 12:53:33
【问题描述】:
这个问题应该比我上几个问题简单一点。我在我的程序中实现了以下工作队列:
池.h:
// tpool class
// It's always closed. :glasses:
#ifndef __POOL_H
#define __POOL_H
class tpool {
public:
tpool( std::size_t tpool_size );
~tpool();
template< typename Task >
void run_task( Task task ){
boost::unique_lock< boost::mutex > lock( mutex_ );
if( 0 < available_ ) {
--available_;
io_service_.post( boost::bind( &tpool::wrap_task, this, boost::function< void() > ( task ) ) );
}
}
private:
boost::asio::io_service io_service_;
boost::asio::io_service::work work_;
boost::thread_group threads_;
std::size_t available_;
boost::mutex mutex_;
void wrap_task( boost::function< void() > task );
};
extern tpool dbpool;
#endif
pool.cpp:
#include <boost/asio/io_service.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "pool.h"
tpool::tpool( std::size_t tpool_size ) : work_( io_service_ ), available_( tpool_size ) {
for ( std::size_t i = 0; i < tpool_size; ++i ){
threads_.create_thread( boost::bind( &boost::asio::io_service::run, &io_service_ ) );
}
}
tpool::~tpool() {
io_service_.stop();
try {
threads_.join_all();
}
catch( ... ) {}
}
void tpool::wrap_task( boost::function< void() > task ) {
// run the supplied task
try {
task();
} // suppress exceptions
catch( ... ) {
}
boost::unique_lock< boost::mutex > lock( mutex_ );
++available_;
}
tpool dbpool( 50 );
但问题是,并非我对run_task() 的所有调用都由工作线程完成。我不确定是因为它没有进入队列还是因为创建它的线程退出时任务消失了。
所以我的问题是,我有什么特别需要给boost::thread 让它等到队列解锁的吗?进入队列的任务的预期生命周期是多少?当创建它们的线程退出时,任务是否超出范围?如果是这样,我该如何防止这种情况发生?
编辑:我对我的代码进行了以下更改:
template< typename Task >
void run_task( Task task ){ // add item to the queue
io_service_.post( boost::bind( &tpool::wrap_task, this, boost::function< void() > ( task ) ) );
}
现在看到所有条目都输入正确。但是,我还有一个挥之不去的问题:添加到队列中的任务的生命周期是多少?一旦创建它们的线程退出,它们就不再存在了吗?
【问题讨论】:
标签: c++ multithreading threadpool boost-asio boost-thread