boost::asio::thread_pool
是一个非常有用的线程池实例,但是它不限制任务数量。您可以在其中发布任意数量的任务。有时会占用大量内存。而且我想使用boost::asio::thread_pool
来实现一个限制任务数量的线程池。
这是我的代码:
class threadpool{
public:
threadpool(int n):threads(n),thnum(n),count(0),stopflag(false){}
~threadpool(){
stop();
}
void stop(){
stopflag=true;
cond.notify_all();
threads.stop();
}
template<typename F, typename...Args>
void post(F &&f, Args&&...args) {
boost::unique_lock<boost::mutex> lock(mute);
cond.wait(lock,[this]{
return stopflag || count < 2*thnum;// task number less than 2x thread number
});
++count;
// The next line doesn't compile
boost::asio::post(threads,boost::bind(&threadpool::post_func,this,std::forward<F>(f), std::forward<Args>(args)...));
}
private:
boost::asio::thread_pool threads;
int count;// task number
int thnum;// thread number
bool stopflag;
boost::mutex mute;
boost::condition_variable_any cond;
template<typename F, typename...Args>
void post_func(F &&f, Args&&...args){
boost::unique_lock<boost::mutex> lock(mute);
--count;
cond.notify_one();
lock.unlock();
auto func=boost::bind(std::forward<F>(f), std::forward<Args>(args)...);
func();
}
};
然后我得到了
../thpl.cpp: In instantiation of 'void threadpool::post(F&&, Args&& ...) [with F = void (print_task::*)(); Args = {print_task*}]':
../thpl.cpp:61:34: required from here
../thpl.cpp:25:46: error: no matching function for call to 'bind(<unresolved overloaded function type>, threadpool*, void (print_task::*)(), print_task*)'
boost::asio::post(threads,boost::bind(&threadpool::post_func,this,std::forward<F>(f), std::forward<Args>(args)...));
~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
后面有很多note:
。
那么如何将Boost :: bind与可变长度模板参数一起使用?我做错了什么?