除了“async_wait”之外它怎么能做其他工作?在一个线程中使用 boost.asio.deadline_timer
我重写了 boost.asio 示例“Timer.3 - 将参数绑定到处理程序”。我认为“工人”可以永远工作,“打印”可以每秒调用。但“打印”只被调用一次。我很难思考为什么。
如果这不起作用,我该如何在一个线程中做除“async_wait”之外的其他事情。
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int num = 0;
void worker(){
while(1){
++num;
}
}
void print(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* t, int* count)
{
std::cout << *count << "\n";
++(*count);
t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
t->async_wait(boost::bind(
print, boost::asio::placeholders::error, t, count
));
if(*count == 1){
worker();
}
}
int main()
{
boost::asio::io_service io;
int count = 0;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait(boost::bind(print,
boost::asio::placeholders::error, &t, &count
));
io.run();
std::cout << "Final count is " << count << "\n";
return 0;
}
I rewrite a boost.asio example "Timer.3 - Binding arguments to a handler". I think "worker" can work forever and "print" can be called each second. But "print" only is called once. It is very diffcult for me to think why.
If this can't work,how can I do other things except "async_wait" in one single thread.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int num = 0;
void worker(){
while(1){
++num;
}
}
void print(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* t, int* count)
{
std::cout << *count << "\n";
++(*count);
t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
t->async_wait(boost::bind(
print, boost::asio::placeholders::error, t, count
));
if(*count == 1){
worker();
}
}
int main()
{
boost::asio::io_service io;
int count = 0;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait(boost::bind(print,
boost::asio::placeholders::error, &t, &count
));
io.run();
std::cout << "Final count is " << count << "\n";
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有一个无限循环
,因此第一次调用 print() 时控件永远不会返回。
You have an infinite loop
so control never returns the first time
print()
is invoked.