您的位置:首页 > 运维架构 > Linux

boost asio timer,linux time and timer

2015-03-13 22:15 316 查看
boost 定时器有同步和异步两种:
同步定时器

编译-lboost_system

运行export  LD_LIBRARY_PATH=/usr/local/include/boost_1_57_0-x86/__INSTALL/lib

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

using namespace boost;
using namespace boost::asio;
int main() {

io_service ios;
deadline_timer t(ios,posix_time::seconds(2));

t.wait();

return 0;
}


异步定时器

编译-lboost_system

运行export  LD_LIBRARY_PATH=/usr/local/include/boost_1_57_0-x86/__INSTALL/lib

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

using namespace boost;
using namespace boost::asio;

void call_func1(const  boost::system::error_code& e)
{

printf("%s\n",e.message().c_str());//Success
}

int main() {

io_service ios;
deadline_timer t(ios,posix_time::seconds(2));

t.async_wait(call_func1);
ios.run();

return 0;
}
ff
//
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //

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

class printer
{
public:
printer(boost::asio::io_service& io)
: timer_(io, boost::posix_time::seconds(1)),
count_(0)
{
timer_.async_wait(boost::bind(&printer::print, this));
}

~printer()
{
std::cout << "Final count is " << count_ << "\n";
}

void print()
{
if (count_ < 5)
{
std::cout << count_ << "\n";
++count_;

timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(boost::bind(&printer::print, this));
}
}

private:
boost::asio::deadline_timer timer_;
int count_;
};
int main()
{
boost::asio::io_service io;
printer p(io);
io.run();

return 0;
}

#include <iostream>
#include <boost/ref.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost;
using namespace boost::asio;

void call_func1(io_service &ios)
{
try {
std::cout << "call_func1" << std::endl;

} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
}

void call_func2()
{
try {
std::cout << "call_func2" << std::endl;

} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
}

class a_timer
{
private:
int count, count_max;
boost::function<void()> f;
boost::asio::deadline_timer t;

public:
template<typename F>
a_timer(io_service &ios, int x, F func): f(func), count_max(x), count(0),
t(ios, boost::posix_time::millisec(1000)) {
t.async_wait(boost::bind(&a_timer::call_func, this, boost::asio::placeholders::error));
}

void call_func(const boost::system::error_code&)
{
if (count >= count_max) {
return;
}
++count;
f();
t.expires_at(t.expires_at() + boost::posix_time::millisec(500));
t.async_wait(boost::bind(&a_timer::call_func, this, boost::asio::placeholders::error));
}

};

int main()
{
io_service ios;
a_timer at1(ios, 2, boost::bind(call_func1, boost::ref(ios)));
a_timer at2(ios,3,call_func2);

ios.run();
}


另外,linux应用层的系统调用2和c库3的定时器函数总结如下:

计时函数@REF1

time(2) / time_t (秒)
ftime(3) / struct timeb (毫秒)
gettimeofday(2) / struct timeval (微秒)
clock_gettime(2) / struct timespec (纳秒)
gmtime / localtime / timegm / mktime / strftime / struct tm (这些与当前时间无关)

定时函数

sleep
alarm
usleep
nanosleep
clock_nanosleep
getitimer / setitimer
timer_create / timer_settime / timer_gettime / timer_delete
timerfd_create / timerfd_gettime / timerfd_settime

alarm函数:

alarm超时信号会终止主线程的sleep函数
#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>

using namespace std;

void my_alarm_handler(int a){
cout<<" my_alarm_handler"<<endl;
alarm(3);//更改为2秒调用一次Timer
}
static void * thread_start1(void *arg)
{
while(1)
{
int iLeft=sleep(6);
cout<<"thread1,sleep,iLeft= "<<iLeft<<endl;
}
}
static void * thread_start2(void *arg)
{
while(1)
{
int iLeft=sleep(6);
cout<<"thread2,sleep,iLeft= "<<iLeft<<endl;
}
}
int main(){
pthread_t t1;
pthread_create(&t1, NULL, &thread_start1, NULL);
pthread_t t2;
pthread_create(&t2, NULL, &thread_start2, NULL);

cout << "1" <<endl;
signal( SIGALRM, my_alarm_handler);
cout << "2" <<endl;
alarm(3);
cout << "3" <<endl;

while(1)
{
int iLeft=sleep(6);
cout<<"main,sleep,iLeft= "<<iLeft<<endl;
}
return 0;
}

# ./ab 
1
2
3

 my_alarm_handler
main,sleep,iLeft= 3

 my_alarm_handler
main,sleep,iLeft= 3
thread2,sleep,iLeft= 0
thread1,sleep,iLeft= 0

 my_alarm_handler
main,sleep,iLeft= 3

thread2,sleep,iLeft= 0
thread1,sleep,iLeft= 0
 my_alarm_handler
main,sleep,iLeft= 3
可见,

main thread的sleep会被alarm中断掉而返回,每次都执行sleep了一半

其他thread的sleep函数则正常

timer_create / timer_settime / timer_gettime / timer_delete

#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>        /* Definition of uint64_t */
#include <time.h>

#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)

static void
print_elapsed_time(void)
{
static struct timespec start;
struct timespec curr;
static int first_call = 1;
int secs, nsecs;

if (first_call) {
first_call = 0;
if (clock_gettime(CLOCK_MONOTONIC, &start) == -1)
handle_error("clock_gettime");
}

if (clock_gettime(CLOCK_MONOTONIC, &curr) == -1)
handle_error("clock_gettime");

secs = curr.tv_sec - start.tv_sec;
nsecs = curr.tv_nsec - start.tv_nsec;
if (nsecs < 0) {
secs--;
nsecs += 1000000000;
}
printf("%d.%03d: ", secs, (nsecs + 500000) / 1000000);
}

int
main(int argc, char *argv[])
{
struct itimerspec new_value;
int max_exp, fd;
struct timespec now;
uint64_t exp, tot_exp;
ssize_t s;

if ((argc != 2) && (argc != 4)) {
fprintf(stderr, "%s init-secs [interval-secs max-exp]\n",
argv[0]);
exit(EXIT_FAILURE);
}

if (clock_gettime(CLOCK_REALTIME, &now) == -1)
handle_error("clock_gettime");

/* Create a CLOCK_REALTIME absolute timer with initial
expiration and interval as specified in command line */

new_value.it_value.tv_sec = now.tv_sec + atoi(argv[1]);
new_value.it_value.tv_nsec = now.tv_nsec;
if (argc == 2) {
new_value.it_interval.tv_sec = 0;
max_exp = 1;
} else {
new_value.it_interval.tv_sec = atoi(argv[2]);
max_exp = atoi(argv[3]);
}
new_value.it_interval.tv_nsec = 0;

fd = timerfd_create(CLOCK_REALTIME, 0);
if (fd == -1)
handle_error("timerfd_create");

if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1)
handle_error("timerfd_settime");

print_elapsed_time();
printf("timer started\n");

for (tot_exp = 0; tot_exp < max_exp;) {
s = read(fd, &exp, sizeof(uint64_t));
if (s != sizeof(uint64_t))
handle_error("read");

tot_exp += exp;
print_elapsed_time();
printf("read: %llu; total=%llu\n",
(unsigned long long) exp,
(unsigned long long) tot_exp);
}

exit(EXIT_SUCCESS);
}
./ab 3 1 6
0.000: timer started
3.000: read: 1; total=1
4.000: read: 1; total=2
5.000: read: 1; total=3
6.000: read: 1; total=4
7.001: read: 1; total=5
8.001: read: 1; total=6


----------------------------------------------------------

@REF1
http://blog.csdn.net/Solstice/article/details/6173563
陈硕
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: