boost::asio::io_service::定时器任务队列
2024-09-01 09:22:27
使用io_service和定时器写的一个同步和异步方式的任务队列
#pragma once #include <string>
#include <iostream>
#include <functional>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <deque>
#include <mutex>
class task
{
public:
task();
~task(); void init();
void poll();
void run(); void post(std::string str); void handle_task(const boost::system::error_code& error);
protected:
boost::asio::io_service m_ioServer; std::deque<std::string> m_deque; boost::asio::deadline_timer m_taskTimer;
int m_taskTimeOut; std::mutex m_lock;
};
typedef boost::shared_ptr<task> taskRef;
#include "pch.h"
#include "task.h" task::task():
m_taskTimer(m_ioServer),
m_taskTimeOut()
{
} task::~task()
{
} void task::init()
{
m_taskTimer.expires_from_now(boost::posix_time::seconds(m_taskTimeOut));
m_taskTimer.async_wait(boost::bind(&task::handle_task, this, boost::asio::placeholders::error));
} void task::poll()
{
m_ioServer.poll();
} void task::run()
{
m_ioServer.run();
} void task::handle_task(const boost::system::error_code& error)
{
if (!error)
{
while (!m_deque.empty()) {
std::lock_guard<std::mutex> mut(m_lock);
std::string str = m_deque.front();
printf("task work %s\n", str.c_str());
}
m_taskTimer.expires_from_now(boost::posix_time::seconds(m_taskTimeOut));
m_taskTimer.async_wait(boost::bind(&task::handle_task, this, boost::asio::placeholders::error));
}
} void task::post(std::string str)
{
std::lock_guard<std::mutex> mut(m_lock);
m_deque.push_back(str);
}
#pragma once
#include "task.h"
#include <boost/thread/thread.hpp>
class TaskApp { public:
TaskApp() {};
~TaskApp() {}; void setTask() {
mTaskRef = taskRef(new task());
mTaskRef->init(); boost::thread thrd(&TaskApp::run, this);
} void run() { //同步阻塞方式
mTaskRef->run(); /* //异步方式
while (1)
{
mTaskRef->poll();
}*/
} void post_task(std::string str)
{
mTaskRef->post(str);
} protected:
taskRef mTaskRef;
};
int main()
{
TaskApp taskApp;
taskApp.setTask();
while ()
{
taskApp.post_task("hello");
std::this_thread::sleep_for(std::chrono::seconds());
}
}
最新文章
- jquery.cookie的使用
- fedora配置163为yum的源
- GNURadio 使用问题
- 如何 实现PHP多版本的 共存 和 切换?
- loadRunner 负载机连接错误分析
- Linux下VirtualBox出现kernel driver not installed的解决方法
- vijosP1053 Easy sssp
- 04737_C++程序设计_第9章_运算符重载及流类库
- uva11806
- Struts(十四):通用标签-form表单
- css关于浮动的高度塌陷
- 思路:controller层:后台如何取值 前端如何给name赋值 例如是id赋值还是自己随意定义
- 学习笔记之Supervised Learning with scikit-learn | DataCamp
- ASPxCallback组件(珍藏版)
- 四则运算app总结
- highchart 横轴纵轴数据
- BZOJ4872: [Shoi2017]分手是祝愿【概率期望DP】【思维好题】
- 1、JDK自带注解
- Docker容器和本机之间的文件传输 使用Docker部署Tomcat项目
- C - Ilya And The Tree Codeforces Round #430 (Div. 2)
热门文章
- Metasploit工具----漏洞利用模块
- IBM MQ reason code list
- Linux 中 Xampp 的 https 安全证书配置
- TensorFlow2.0(1):基本数据结构—张量
- 实现一个正则表达式引擎in Python(二)
- kubernetes实战(二十六):kubeadm 安装 高可用 k8s v1.16.x dashboard 2.x
- django开发后台接口error 10053/10054
- 从零开始用golang创建一条简单的区块链
- 配置eclipse编写html/js/css/jsp/java时自动提示
- 【SQL基础】char,nchar,vchar,nvchar之间的区别