使用 boost::asio 提升线程池
boost threadpool using boost::asio
我正在尝试使用带有工作队列的boost asio创建提升线程池。但是我卡在某一点上,我需要一个监视功能,它应该继续运行并跟踪队列。我不确定我该怎么写,目前我把它放在我的线程池类中。我也在尝试编写具有全局函数的分离线程。有人可以提出任何建议吗?
#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include<memory>
#include<vector>
#include<list>
using namespace std;
class threadWork
{
public:
virtual void run()=0;
};
class thread_pool
{
private:
boost::asio::io_service io_service_;
boost::asio::io_service::work work_;
boost::thread_group threads_;
std::size_t available_;
boost::mutex mutex_;
list<shared_ptr<threadWork>> workQueue;
public:
thread_pool( std::size_t pool_size ) : work_( io_service_ ), available_( pool_size )
{
for ( std::size_t i = 0; i < pool_size; ++i )
{
threads_.create_thread( boost::bind( &boost::asio::io_service::run, &io_service_ ) );
}
}
~thread_pool()
{
io_service_.stop();
try
{
threads_.join_all();
}
catch ( ... ) {}
}
void enqueue(shared_ptr<threadWork> work)
{
workQueue.push_back(work);
}
void keepRunning() // how to call this ?
{
while(true)
{
boost::unique_lock< boost::mutex > lock( mutex_ );
if ( 0 == available_ ) // If no threads are available, then sleep.
{
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
else
{
if(workQueue.empty() != true)
{
--available_;
io_service_.post( boost::bin(&thread_pool::wrap_task,this , workQueue));
workQueue.pop_front();
}
}
}
}
private:
void wrap_task(list<shared_ptr<threadWork>>& workQueue )
{
try
{
workQueue.front()->run(); // Run the user supplied task.
}
catch ( ... ) // Suppress all exceptions.
{
}
boost::unique_lock< boost::mutex > lock( mutex_ );
++available_;
}
};
class someWork:public threadWork
{
public:
virtual void run()
{
cout<<"some long task n";
boost::this_thread::sleep(boost::posix_time::milliseconds(5000));
}
};
int main()
{
thread_pool pool(10);
pool.keepRunning(); // this stuck code so where to start this ?
shared_ptr<threadWork> w(new someWork);
pool.enqueue(w);
return 0;
}
您可以使用
boost::asio::deadline_timer
定期让io_service
更新表示队列长度的原子变量。类成员函数可以按需返回队列长度(按值)。
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 提升 ASIO - io_service 不要等待连接到线程
- ASIO signal_set多个 IO 线程不可靠,具体取决于代码顺序?
- 将更高的优先级设置为 boost::asio 线程处理进程
- asio 链对象线程安全吗?
- asio::io_service 具有多个线程的优先级队列处理
- boost信号和插槽在不同的线程中不工作(使用boost::asio::io_service)
- 调用boost.asio的异步函数时,线程是什么时候创建的
- 调用socket.remote_endpoint(提升 asio 库)线程安全性
- 使用线程池提升 ASIO 多线程 TCP 服务器
- 重写多线程事件驱动的C 程序以使用单线程Boost :: Asio
- 在具有许多内核的计算机上,使用 Boost ASIO 只能使用 1 个线程
- 如何将每线程用户数据传递到ASIO处理程序中
- 提高 ASIO stream_descriptor和事件 FD 线程安全性
- 提升 asio io_service多线程性能不佳
- 在std ::线程中升级ASIO阻止操作,而不是使用异步方法
- 是boost :: asio :: thread_pool线程在多个线程上发布任务时的安全性
- Boost.Asio、tcp::iostream 和多线程
- Boost.Asio:由于线程退出或应用程序请求,I/O 操作已中止
- boost::asio绞线缠绕的线程无法立即工作