我正在使用C++进行项目工作。如何使用Boost库创建TimerHandler
我想被称为指定时间后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是 使用隐藏线);
- 如果我们必须 引入一个额外的线程做 工作,你会介意为我写下 伪代码吗?
谢谢。
Peter
感谢您的回复。我试图将新线程应用于我的示例。但我不知道如何,请你帮我一下? – 2011-05-17 15:49:40
@OcrunC,请忽略我上面的评论。我得到了它的工作。谢谢。 – 2011-05-17 21:31:15
你会介意看看我的另一篇文章:http://stackoverflow.com/questions/6076524/why-my-eventtimer-implemented-by-boostasioio-service-and-boostdeadline-time – 2011-05-20 19:33:33