c++ - 如何使用 Boost 库创建 TimerHandler

标签 c++ boost timer boost-asio handler

我正在使用 C++ 开发一个项目。

我希望在指定时间后调用一个 TimerHandler,但同时我不想阻塞当前线程或以下代码中 io.run() 之后的任何代码:

#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

class TimerTest
{
public:
    static void PrintOutTimerHandler(const boost::system::error_code&, const std::string& message)
    {
        std::cout << "PrintOutTimerHandler called: " << ", message: " << message << std::endl;
    }

    void run()
    {
        boost::asio::io_service io;
        boost::asio::deadline_timer dt(io, boost::posix_time::seconds(5));

        std::cout << "Start:\t" << std::endl;

        dt.async_wait(boost::bind(PrintOutTimerHandler, boost::asio::placeholders::error, std::string("here is the message")));

        // Do some job here
        for (int i = 0; i < 1000000; ++i)
            ++i, --i;

        std::cout << "End:\t" << std::endl;

        io.run();

        std::cout << "When to reach here 1: " << std::endl;
    }
};

int main()
{
    TimerTest tt;
    tt.run();

    std::cout << "When to reach here 2: " << std::endl;

    return 0;
}

/* Current output:
Start:
End:
PrintOutTimerHandler called: , message: here is the message
When to reach here 1:
When to reach here 2:
 */

/* Expected output:
Start:
End:
When to reach here 1:
When to reach here 2:
PrintOutTimerHandler called: , message: here is the message
 */

我想我已经说清楚了。我的问题是:

  • 如果不用 引入一个新线程,比如 Flex ActionScript,这是最好的,但是 我猜不是(我猜 ActionScript 是 使用隐藏线程);
  • 如果我们不得不 引入一个额外的线程来做 工作,你介意写下 给我的伪代码?

谢谢。

彼得

最佳答案

这是一个例子。在单独的线程中运行 io_service

asio::io_service io_service;
asio::thread t(boost::bind(&asio::io_service::run, &io_service));

或者在线程组中运行

boost::thread_group threads;
for (std::size_t i = 0; i < my_thread_count; ++i)
    threads.create_thread(boost::bind(&asio::io_service::run, &io_service));

请记住,您的主线程应该始终运行,因为当它存在时,所有产生的线程也会退出。

希望对您有所帮助。

关于c++ - 如何使用 Boost 库创建 TimerHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6026467/

相关文章:

c++ - Boost::Asio:为什么 async_write 在通过给定套接字发送缓冲区时会截断缓冲区?

c# 禁用事件一段时间

.net - 如何向我的 C++ 项目添加计时器?

c++ - 从堆和内存泄漏中删除 C++ 数组

C++:为什么返回 false 的集合顺序的仿函数只允许将一个元素添加到集合中?

c++ - boost::log 是否可以在每次应用程序运行时旋转文件?

c++ - 如何将 boost::crc_optimal 与二进制数组一起使用(0's and 1' s 的数组)

c# - C# 中使用 System.Threading.Timer 的延迟队列

c++ - 类模板的显式实例化而不是实例化构造函数

c++ - C++ bool 数据类型的奇怪行为