1 源碼
//參數(shù)傳入 Binding arguments to a handler
#include "stdafx.h"
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
//因?yàn)橐_啟一個(gè)重復(fù)的計(jì)時(shí)液茎,所以需要把timer的指針也傳進(jìn)來
void print(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* t, int* count)
{
if (*count < 5)
{
std::cout << *count << std::endl;
++(*count);
t->expires_at(t->expires_at() + boost::posix_time::seconds(1)); //重新設(shè)定計(jì)時(shí)蝌以,這里加上了超時(shí)時(shí)間派阱,以保證下次計(jì)時(shí)仍然是1s,不會(huì)因?yàn)槌绦驁?zhí)行的耗時(shí)嚣州,導(dǎo)致時(shí)間不準(zhǔn)確。
t->async_wait(boost::bind(print,
boost::asio::placeholders::error, t, count));
}
}
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));//傳入?yún)?shù)count,參數(shù)傳入的順序與回調(diào)函數(shù)是一致的
io.run();
std::cout << "Final count is " << count << std::endl;
getchar(); //暫停程序。
return 0;
}
2 運(yùn)行結(jié)果
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者