summaryrefslogtreecommitdiff
path: root/utils/Timer.cc
blob: c2b4d11d9ba9af49f73270bd9b5f16b90d1070c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/*
 *	CENA C++ Utilities
 *
 *	by Stephane Chatty
 *
 *	Copyright 1992-1996
 *	Centre d'Etudes de la Navigation Aerienne (CENA)
 *
 *	timers
 *
 *	$Id$
 *	$CurLog$
 */

#ifdef __GNUG__
#pragma implementation "Timer.h"
#endif
#include "Timer.h"
#include "Signal.h"
#include "List.h"

#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <stdio.h>

/*!class IvlCoreTimer
The implementation of \typ{IvlCoreTimer} is a bit tricky, because it tries to be fast.
Here is the basic idea: active timers are stored in a list, sorted by increasing time-out
times. When a signal occurs, all timers whose time-out time is smaller than the current
time are notified and removed from the list, then they are inserted again.
Then, the optimizations. First, we distinguish the first active timer from the others.
It is not in the list, but has a pointer of its own. Second, we do not remove timers
from the list when they are stopped, but rather flag them as inactive. It means that
we have to test a flag when extracting timers from the list. It also means that we can
have many occurences of the same timer in the list, only one being in the right place.
Even worse, when such a timer is inserted again in the list, there is no way of knowing
that the other occurences are wrong: it is the same object, and it no longer flagged as
inactive. However, if we remove all encountered inactive timers when inserting one,
and if we make sure that a timer is flagged as inactive when we insert it, all wrong
occurences before the right one will be removed. 
!*/

/*?class IvlCoreTimer
Timers are a means to manage or one more periodic tasks in a program.
The class \typ{IvlCoreTimer} is a base class for all kinds of timers. It provides
the basic storing and scheduling of timers, as well as a set of member functions
available to the user, but does not provide the actual, system dependent, timing
scheme.
\typ{IvlCoreTimers} were not designed to be used as is, but only to be derived
in order to implement a specific timing scheme.
For instance, the class \var{IvlBaseTimer} is derived from it and implements
signal-based timers (see next section). Building such derived class is very rare,
and it has only be done for timers based on the Unix \com{select} system call,
in the Unix Channel library.

A timer is created with a period expressed in milliseconds. It will then
periodically call the member function \fun{Handle}, which should be redefined
in derived classes.
Timers are activated at creation time. They are disactivated, but not destroyed, after
their last pulse.
The member function \fun{Handle} is called when a timer is triggered.
It has a time parameter: it is passed the
current (absolute) time when the signal was received from the system. However,
several timers may be triggered at the same time.
If one of them has a slow \fun{Handle}, the time passed to the next ones no more
corrresponds to the current time. If you want to know the exact time, and you are
not sure of the behaviour of the other timers, it is preferable to use a \typ{IvlTimeStamp}.
?*/

/*?class IvlTimerSet
The class \typ{IvlTimerSet} is the data structure used by the class \typ{IvlCoreTimer}
to manage a set of timers. Each different implementation of timers should work
with one such timer set, which is passed to the constructor of \typ{IvlCoreTimer}.
?*/

#ifdef DOC
/*?
Create an empty \typ{IvlTimerSet}.
?*/
IvlTimerSet :: IvlTimerSet ()
{
}

#endif	/* DOC */

/*!
Remove and return the first active timer in the active timer list.
Timers in that list can actually be inactive.
!*/
/*?hidden?*/
IvlCoreTimer*
IvlTimerSet :: ExtractNextActive ()
{
	IvlCoreTimer* t;

	/* all entries of OtherTimers are valid pointers,
	    hence t == 0 iff OtherTimers is empty */
#ifndef CPLUS_BUG19
	while ((t = OtherTimers.RemoveFirst ()) && (t->StatusFlag != IvlCoreTimer::Active))
#else
	while ((t = (IvlCoreTimer*) OtherTimers.RemoveFirst ()) && (t->StatusFlag != IvlCoreTimer::Active))
#endif
		;

	return t;
}

/*!
This function is called by the signal handler. The first active timer is expired
and scheduled again. Then all the timers whose expiration time is earlier
that the current time are removed from the list, expired and scheduled again.
The first non-expired timer, if any, is removed from the list and saved 
as the first active timer. 
Finally, the alarm is set up to expire at the expiration time of the new first
active timer.
!*/
/*?
This function should be called by the underlying timing scheme when one
or more timer has expired. It decides which timers should be triggered,
and prepares the set of timers for the next call.
?*/
void
IvlCoreTimer :: Fire (IvlTimerSet* s)
{
	IvlCoreTimer*& first = s->FirstTimer;

	/* If the first timer is not mature yet, ignore this call */
	if (!first)
		return;

	IvlTimeStamp now;
#if defined(sun) && defined(__svr4__)
	/* add tolerance because Solaris sends signals before the expected time (bug #1164919)*/
	if (first->NextDate > now + 5) {
#else
	if (first->NextDate > now) {
#endif
		/* this should never happen, except with bogus Solaris... */
		first->SetAlarm (first->NextDate - now);
//		fprintf (stderr, "%d > %d\n", first->NextDate, now);
		return;
	}

	/**** Handle the first timer ****/
	/* first, reschedule it ASAP*/
	first->Reschedule ();
	/* first is not valid, but Handle will perhaps call Stop or Restart and do the job */
	s->FirstIsUpdated = false;
	/* then, call the user's code */
	first->Handle (now);

	/* handle all other expired timers. */
	IvlCoreTimer* t;
	while (t = s->ExtractNextActive ()) {
		/* Problem : if one Handle () is long, "now"  will then be wrong. */
		if (t->NextDate > now) {
//			fprintf (stderr, "%x is not ready\n", t);
			break;
		}
//		fprintf (stderr, "%x is ready\n", t);
		t->Reschedule ();
		t->Handle (now);
	}

	/* don't try and update first if it's alredy been done! */
	if (s->FirstIsUpdated)
		return;

	if (t) {
		IvlTimeStamp then;
		t->SetAlarm (t->NextDate - then);
	} else if (first) {
		/* we need a valid timer just to be able to call StopAlarm */
		/* if first is null, StopAlarm has already been called (?) */
		first->StopAlarm ();
	}

	first = t;
}

#ifndef CPLUS_BUG19

/*?hidden?*/
int
IvlCoreTimer :: IsInactive (IvlCoreTimer* t)
{
	return (t->StatusFlag != Active);
}

#else

/*?hidden?*/
int
IvlCoreTimer :: IsInactive (IvlListItem* t)
{
	return (((IvlCoreTimer*) t)->StatusFlag != Active);
}

#endif	/* CPLUS_BUG19 */

/*?
Create a timer with that will time out every \var{period} milliseconds, and at most
\var{pulses} times. This timer will be managed by the timer set \var{s}.
{\em This constructor is only useful when deriving new timers based on a new
timing scheme.}
?*/
IvlCoreTimer :: IvlCoreTimer (Millisecond period, int pulses, IvlTimerSet* s)
: MySet (s),
  StatusFlag (Active),
  Period (period > 0 ? period : 10),
  PulsesLeft (pulses)
{
}

/*?nodoc?*/
IvlCoreTimer :: ~IvlCoreTimer ()
{
	/* the timer has to be stopped in the derived class */
	/* Remove all entries pointing to inactive timers, including this one */
	if (MySet)
		MySet->OtherTimers.Remove (IsInactive, IvlList::All);
}

/*?
Change the period of a timer. The new period will not be taken into account
before the next time-out.
?*/
void
IvlCoreTimer :: ChangePeriod  (Millisecond period)
{
	IvlSignalBlocker b (SigAlrm);
	Period = period;
}

/*?
Change the number of times a timer will go off before stopping. If
the timer is stopped, it is not restarted.
?*/
void
IvlCoreTimer :: ChangeNbPulses  (int nb)
{
	IvlSignalBlocker b (SigAlrm);
	PulsesLeft = nb;
}

/*?
Stop this timer if it was running, then start it with its current period.
This function can be used to reset a timer to the beginning of a period.
?*/
void
IvlCoreTimer :: Restart ()
{
	if (PulsesLeft == 0)
		return;

	/* this function could be optimized: sometimes SetAlarm is called twice. */
	IvlSignalBlocker b (SigAlrm);
	if (StatusFlag == Active)
		Stop ();
	Activate ();
}

/*!
This function sets up a timer that was previously inactive.
The timer is inserted in the list of active timers, and if it is the
first one, the alarm is updated.
!*/
/*?hidden?*/
void
IvlCoreTimer :: Activate ()
{
	if (!MySet)
		return;
	IvlTimeStamp now;
	NextDate = now + Period;
	IvlCoreTimer*& first = MySet->FirstTimer;
	if (!first) {
		first = this;
		SetAlarm (Period);
	} else if (NextDate < first->NextDate ) {
		SetAlarm (Period);
		MySet->OtherTimers.Prepend (first);
		first = this;
	} else
		Schedule (NextDate);
	StatusFlag = Active;
	MySet->FirstIsUpdated = true;
}

/*?hidden?*/
void
IvlCoreTimer :: Reschedule ()
{
	if (PulsesLeft == 0)	// this should not happen...
		return;

	if (PulsesLeft > 0)
		if (--PulsesLeft == 0)
			return;

	Schedule (NextDate + Period);
}

/*?hidden?*/
void
IvlCoreTimer :: Schedule (Millisecond when)
{
	NextDate = when;

	/* temporarily set status to inactive so that obsolete entries
	    in OtherTimers pointing to this timer can be removed */
	StatusFlag = Inactive;
	IvlListOf <IvlCoreTimer>& others = MySet->OtherTimers;

#ifndef CPLUS_BUG19
	IvlListIterOf <IvlCoreTimer> li (others);
	IvlListIterOf <IvlCoreTimer> lj (others);
#else
	IvlListIter li (others);
	IvlListIter lj (others);
#endif

	while (++li) {
		/* while we're at it, remove inactive timers from the list */
#ifndef CPLUS_BUG19
		IvlCoreTimer* cur = *li;
#else
		IvlCoreTimer* cur = (IvlCoreTimer*) *li;
#endif
		if (cur->StatusFlag != Active) {
			others.RemoveAfter (lj);
			li = lj;
		} else if (cur->NextDate < NextDate)
			++lj;
		else
			break;
	}
	others.InsertAfter (lj, this);
	StatusFlag = Active;
}

/*?
Stop a timer.
This timer will not deliver any signal until \fun{Restart} is called.
?*/
void
IvlCoreTimer :: Stop ()
{
	if (StatusFlag != Active)
		return;

	IvlSignalBlocker b (SigAlrm);
	IvlCoreTimer*& first = MySet->FirstTimer;

	StatusFlag = Inactive;

	/* if this timer was the first active one, find another one to replace it */
	if (this == first) {
		first = MySet->ExtractNextActive ();
		if (first == 0)
			StopAlarm ();
		else {
			IvlTimeStamp now;
			first->SetAlarm (first->NextDate - now);
		}
	}
	MySet->FirstIsUpdated = true;
}

/*?
Wait for this timer to expire. If it is stopped, return immediately.
?*/
void
IvlCoreTimer :: Wait ()
{
	if (StatusFlag != Active)
		return;

	Millisecond next_date = NextDate;
	for (;;) {
		if (wait (0) >= 0)	// not an interrupt
			continue;
		if (StatusFlag != Active || next_date != NextDate)
			return;
	}
}

#ifdef DOC
/*?nextdoc?*/
Millisecond
IvlCoreTimer :: GetPeriod () const
{
}

/*?
Get the period (resp. the number of pulses to go) of a timer.
?*/
int
IvlCoreTimer :: GetNbPulses () const
{
}

/*?
Get the status of a timer. The returned value is \var{Active} or \var{Inactive}.
?*/
timer_status
IvlCoreTimer :: GetStatus () const
{
}

/*?nextdoc?*/
void
IvlCoreTimer :: SetAlarm (Millisecond delay)
{
}

/*?
These two functions hold the implementation of the timing scheme. They
are pure virtual functions, and have to be redefined to implement a specific
scheme. \fun{SetAlarm} should ensure that the function \fun{Fire} will be
called in \var{delay} milliseconds from now. \fun{StopAlarm} should disable such calls.
?*/
void
IvlCoreTimer :: StopAlarm ()
{
}

#endif	/* DOC */

/*?
This virtual function is called when the timer is triggered. It should be
redefined in derived classes to attach a behaviour to a timer.
?*/
void
IvlCoreTimer :: Handle (Millisecond)
{
}

/*?class IvlBaseTimer
The class \typ{IvlBaseTimer} is provided as a base class for signal-based timers.
It comes with a derived class \typ{IvlTimer} that can be used as is.
A timer is created with a period expressed in milliseconds. It will then
periodically call the member function \fun{Handle}, which should be redefined
in derived classes.

Please note that signal-based timers use the signal \var{SIGALRM} and the interval timers
provided by UNIX.
Using them concurrently with system calls such as \fun{sleep} yields
unexpected results.
?*/

IvlSignalHandler* IvlBaseTimer::TimeOutHandler = 0;
IvlTimerSet* IvlBaseTimer::TimerSet = 0;

/*?hidden?*/
void
IvlBaseTimer :: ClassInit ()
{
	TimeOutHandler = new IvlSignalHandler (SigAlrm, &IvlBaseTimer::HandleSignal);
	TimerSet = new IvlTimerSet;
}

/*?
Create a timer that will send a signal every \var{period} milliseconds, \var{pulses} times.
If \var{pulses} is negative, the timer will send signals forever.
Timers are activated at creation time. They are disactivated, but not destroyed, after
their last pulse.
?*/
IvlBaseTimer :: IvlBaseTimer (Millisecond period, int pulses)
: IvlCoreTimer (period, pulses, (TimerSet ? TimerSet : (ClassInit (), TimerSet)))
{
	IvlSignalBlocker b (SigAlrm);

	if (PulsesLeft != 0)
		Activate ();
}

/*?nodoc?*/
IvlBaseTimer :: ~IvlBaseTimer ()
{
	/* stop it */
	if (StatusFlag == Active)
		Stop ();
}

/*?hidden?*/
void
IvlBaseTimer :: StopAlarm ()
{
	struct itimerval itval;
	timerclear (&itval.it_value);
	timerclear (&itval.it_interval);
	setitimer (ITIMER_REAL, &itval, 0);
}

/*?hidden?*/
void
IvlBaseTimer :: SetAlarm (Millisecond delay)
{
	if (delay <= 0) {
		StopAlarm ();
		kill (getpid (), SigAlrm);
		return;
	}

	struct itimerval itval;
	timerclear (&itval.it_interval);
	itval.it_value.tv_sec = delay / 1000;
	itval.it_value.tv_usec = 1000 * (delay % 1000);
	if (setitimer (ITIMER_REAL, &itval, 0) < 0)
		fprintf (stderr, "setitimer failed for interval %d\n", delay);
}

/*!
This function is called by the signal handler. The first active timer is expired
and scheduled again. Then all the timers whose expiration time is earlier
that the current time are removed from the list, expired and scheduled again.
The first non-expired timer, if any, is removed from the list and saved 
as the first active timer. 
Finally, the alarm is set up to expire at the expiration time of the new first
active timer.
!*/
/*?hidden?*/
void
IvlBaseTimer :: HandleSignal (int)
{
	Fire (TimerSet);
}

/*?class IvlTimer
The class \typ{IvlTimer} is a derived class of \typ{IvlBaseTimer} that
can be used without deriving a new class.
Each \typ{IvlTimer} holds a pointer to a function which is called when the timer
expires. This function, which is passed to the constructor, must
take a \typ{Millisecond} argument and return \typ{void}.
?*/

/*?
Create a timer that will expire every \var{period} milliseconds and call
the function \var{handler}.
?*/
IvlTimer :: IvlTimer (Millisecond period, void (*handler) (Millisecond), int pulses)
: IvlBaseTimer (period, pulses),
  Handler (handler)
{
}

/*?nodoc?*/
IvlTimer :: ~IvlTimer ()
{
}

/*?hidden?*/
void
IvlTimer :: Handle (Millisecond ref)
{
	(*Handler) (ref);
}

/*?
Change the handling function of a timer.
?*/
#ifdef DOC
void
IvlTimer :: SetHandler ((void)(*h)(Millisecond))
{
}
#endif