boost::asio::io_service::定时器任务队列

 

 使用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(5)
{
}


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 (1)
    {
        taskApp.post_task("hello");
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

 

posted @ 2019-09-20 16:52  osbreak  阅读(910)  评论(0编辑  收藏  举报