summaryrefslogtreecommitdiff
path: root/lib/common/Timer.cpp
blob: 4b596931551d0d0fac10a7b173d1745627bd456a (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
// --------------------------------------------------------------------------
//
// File
//		Name:    Timer.cpp
//		Purpose: Generic timers which execute arbitrary code when
//			 they expire.
//		Created: 5/11/2006
//
// --------------------------------------------------------------------------

#include "Box.h"

#include <signal.h>

#include "Timer.h"
#include "Logging.h"

#include "MemLeakFindOn.h"

std::vector<Timer*>* Timers::spTimers = NULL;
bool Timers::sRescheduleNeeded = false;

typedef void (*sighandler_t)(int);

// --------------------------------------------------------------------------
//
// Function
//		Name:    static void Timers::Init()
//		Purpose: Initialise timers, prepare signal handler
//		Created: 5/11/2006
//
// --------------------------------------------------------------------------
void Timers::Init()
{
	ASSERT(!spTimers);
	
	#if defined WIN32 && ! defined PLATFORM_CYGWIN
		// no support for signals at all
		InitTimer();
		SetTimerHandler(Timers::SignalHandler);
	#else
		sighandler_t oldHandler = ::signal(SIGALRM, 
			Timers::SignalHandler);
		ASSERT(oldHandler == 0);
	#endif // WIN32 && !PLATFORM_CYGWIN
	
	spTimers = new std::vector<Timer*>;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    static void Timers::Cleanup()
//		Purpose: Clean up timers, stop signal handler
//		Created: 6/11/2006
//
// --------------------------------------------------------------------------
void Timers::Cleanup()
{
	ASSERT(spTimers);
	
	#if defined WIN32 && ! defined PLATFORM_CYGWIN
		// no support for signals at all
		FiniTimer();
		SetTimerHandler(NULL);
	#else
		struct itimerval timeout;
		memset(&timeout, 0, sizeof(timeout));

		int result = ::setitimer(ITIMER_REAL, &timeout, NULL);
		ASSERT(result == 0);

		sighandler_t oldHandler = ::signal(SIGALRM, NULL);
		ASSERT(oldHandler == Timers::SignalHandler);
	#endif // WIN32 && !PLATFORM_CYGWIN

	spTimers->clear();
	delete spTimers;
	spTimers = NULL;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    static void Timers::Add(Timer&)
//		Purpose: Add a new timer to the set, and reschedule next wakeup
//		Created: 5/11/2006
//
// --------------------------------------------------------------------------
void Timers::Add(Timer& rTimer)
{
	ASSERT(spTimers);
	spTimers->push_back(&rTimer);
	Reschedule();
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    static void Timers::Remove(Timer&)
//		Purpose: Removes the timer from the set (preventing it from
//			 being called) and reschedule next wakeup
//		Created: 5/11/2006
//
// --------------------------------------------------------------------------
void Timers::Remove(Timer& rTimer)
{
	ASSERT(spTimers);

	bool restart = true;
	while (restart)
	{
		restart = false;
		for (std::vector<Timer*>::iterator i = spTimers->begin();
			i != spTimers->end(); i++)
		{
			if (&rTimer == *i)
			{
				spTimers->erase(i);
				restart = true;
				break;
			}
		}
	}
		
	Reschedule();
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    static void Timers::Reschedule()
//		Purpose: Recalculate when the next wakeup is due
//		Created: 5/11/2006
//
// --------------------------------------------------------------------------
void Timers::Reschedule()
{
	ASSERT(spTimers);
	if (spTimers == NULL)
	{
		THROW_EXCEPTION(CommonException, Internal)
	}
	if (::signal(SIGALRM, Timers::SignalHandler) != Timers::SignalHandler)
	{
		THROW_EXCEPTION(CommonException, Internal)
	}

	// Clear the reschedule-needed flag to false before we start.
	// If a timer event occurs while we are scheduling, then we
	// may or may not need to reschedule again, but this way
	// we will do it anyway.
	sRescheduleNeeded = false;

	box_time_t timeNow = GetCurrentBoxTime();

	// scan for, trigger and remove expired timers. Removal requires
	// us to restart the scan each time, due to std::vector semantics.
	bool restart = true;
	while (restart)
	{
		restart = false;

		for (std::vector<Timer*>::iterator i = spTimers->begin();
			i != spTimers->end(); i++)
		{
			Timer& rTimer = **i;
			int64_t timeToExpiry = rTimer.GetExpiryTime() - timeNow;
		
			if (timeToExpiry <= 0)
			{
				TRACE3("%d.%d: timer %p has expired, "
					"triggering it\n",
					(int)(timeNow / 1000000), 
					(int)(timeNow % 1000000),
					*i);
				rTimer.OnExpire();
				spTimers->erase(i);
				restart = true;
				break;
			}
			else
			{
				TRACE5("%d.%d: timer %p has not expired, "
					"triggering in %d.%d seconds\n",
					(int)(timeNow / 1000000), 
					(int)(timeNow % 1000000),
					*i,
					(int)(timeToExpiry / 1000000),
					(int)(timeToExpiry % 1000000));
			}
		}
	}

	// Now the only remaining timers should all be in the future.
	// Scan to find the next one to fire (earliest deadline).
			
	int64_t timeToNextEvent = 0;

	for (std::vector<Timer*>::iterator i = spTimers->begin();
		i != spTimers->end(); i++)
	{
		Timer& rTimer = **i;
		int64_t timeToExpiry = rTimer.GetExpiryTime() - timeNow;

		if (timeToExpiry <= 0)
		{
			timeToExpiry = 1;
		}
		
		if (timeToNextEvent == 0 || timeToNextEvent > timeToExpiry)
		{
			timeToNextEvent = timeToExpiry;
		}
	}
	
	ASSERT(timeToNextEvent >= 0);
	
	struct itimerval timeout;
	memset(&timeout, 0, sizeof(timeout));
	
	timeout.it_value.tv_sec  = BoxTimeToSeconds(timeToNextEvent);
	timeout.it_value.tv_usec = (int)
		(BoxTimeToMicroSeconds(timeToNextEvent) % MICRO_SEC_IN_SEC);

	if(::setitimer(ITIMER_REAL, &timeout, NULL) != 0)
	{
		TRACE0("WARNING: couldn't initialise timer\n");
		THROW_EXCEPTION(CommonException, Internal)
	}
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    static void Timers::SignalHandler(unused)
//		Purpose: Called as signal handler. Nothing is safe in a signal
//			 handler, not even traversing the list of timers, so
//			 just request a reschedule in future, which will do
//			 that for us, and trigger any expired timers at that
//			 time.
//		Created: 5/11/2006
//
// --------------------------------------------------------------------------
void Timers::SignalHandler(int iUnused)
{
	// ASSERT(spTimers);
	Timers::RequestReschedule();
}

Timer::Timer(size_t timeoutSecs)
: mExpires(GetCurrentBoxTime() + SecondsToBoxTime(timeoutSecs)),
  mExpired(false)
{
	#ifndef NDEBUG
	struct timeval tv;
	gettimeofday(&tv, NULL);
	if (timeoutSecs == 0)
	{
		TRACE4("%d.%d: timer %p initialised for %d secs, "
			"will not fire\n", tv.tv_sec, tv.tv_usec, this, 
			timeoutSecs);
	}
	else
	{
		TRACE6("%d.%d: timer %p initialised for %d secs, "
			"to fire at %d.%d\n", tv.tv_sec, tv.tv_usec, this, 
			timeoutSecs, (int)(mExpires / 1000000), 
			(int)(mExpires % 1000000));
	}
	#endif

	if (timeoutSecs == 0)
	{
		mExpires = 0;
	}
	else
	{
		Timers::Add(*this);
	}
}

Timer::~Timer()
{
	#ifndef NDEBUG
	struct timeval tv;
	gettimeofday(&tv, NULL);
	TRACE3("%d.%d: timer %p destroyed, will not fire\n",
		tv.tv_sec, tv.tv_usec, this);
	#endif

	Timers::Remove(*this);
}

Timer::Timer(const Timer& rToCopy)
: mExpires(rToCopy.mExpires),
  mExpired(rToCopy.mExpired)
{
	#ifndef NDEBUG
	struct timeval tv;
	gettimeofday(&tv, NULL);
	if (mExpired)
	{
		TRACE4("%d.%d: timer %p initialised from timer %p, "
			"already expired, will not fire\n", tv.tv_sec, 
			tv.tv_usec, this, &rToCopy);
	}
	else if (mExpires == 0)
	{
		TRACE4("%d.%d: timer %p initialised from timer %p, "
			"will not fire\n", tv.tv_sec, tv.tv_usec, this, 
			&rToCopy);
	}
	else
	{
		TRACE6("%d.%d: timer %p initialised from timer %p, "
			"to fire at %d.%d\n", tv.tv_sec, tv.tv_usec, this, 
			&rToCopy, (int)(mExpires / 1000000), 
			(int)(mExpires % 1000000));
	}
	#endif

	if (!mExpired && mExpires != 0)
	{
		Timers::Add(*this);
	}
}

Timer& Timer::operator=(const Timer& rToCopy)
{
	#ifndef NDEBUG
	struct timeval tv;
	gettimeofday(&tv, NULL);
	if (rToCopy.mExpired)
	{
		TRACE4("%d.%d: timer %p initialised from timer %p, "
			"already expired, will not fire\n", tv.tv_sec, 
			tv.tv_usec, this, &rToCopy);
	}
	else if (rToCopy.mExpires == 0)
	{
		TRACE4("%d.%d: timer %p initialised from timer %p, "
			"will not fire\n", tv.tv_sec, tv.tv_usec, this, 
			&rToCopy);
	}
	else
	{
		TRACE6("%d.%d: timer %p initialised from timer %p, "
			"to fire at %d.%d\n", tv.tv_sec, tv.tv_usec, this, 
			&rToCopy, (int)(rToCopy.mExpires / 1000000), 
			(int)(rToCopy.mExpires % 1000000));
	}
	#endif

	Timers::Remove(*this);
	mExpires = rToCopy.mExpires;
	mExpired = rToCopy.mExpired;
	if (!mExpired && mExpires != 0)
	{
		Timers::Add(*this);
	}
	return *this;
}

void Timer::OnExpire()
{
	#ifndef NDEBUG
	struct timeval tv;
	gettimeofday(&tv, NULL);
	TRACE3("%d.%d: timer %p fired\n", tv.tv_sec, tv.tv_usec, this);
	#endif

	mExpired = true;
}