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

 

 使用io_service和定时器写的一个同步和异步方式的任务队列

 

#pragma once

#include <string>
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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::dequestring>            m_deque;

    boost::asio::deadline_timer        m_taskTimer;
    int                                m_taskTimeOut;

    std::mutex                        m_lock;
};
typedef boost::shared_ptr 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 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 mut(m_lock);
    m_deque.push_back(str);
}

 

#pragma once
#include "task.h"
#include 
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));
    }
}

 

转载于:https://www.cnblogs.com/osbreak/p/11558199.html

你可能感兴趣的:(boost::asio::io_service::定时器任务队列)