VirtualBox

source: vbox/trunk/src/libs/xpcom18a4/xpcom/threads/TimerThread.cpp@ 44770

最後變更 在這個檔案從44770是 1,由 vboxsync 提交於 55 年 前

import

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 13.4 KB
 
1/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3 *
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 *
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
11 *
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
16 *
17 * The Original Code is mozilla.org code.
18 *
19 * The Initial Developer of the Original Code is
20 * Netscape Communications Corporation.
21 * Portions created by the Initial Developer are Copyright (C) 2001
22 * the Initial Developer. All Rights Reserved.
23 *
24 * Contributor(s):
25 * Stuart Parmenter <[email protected]>
26 *
27 * Alternatively, the contents of this file may be used under the terms of
28 * either of the GNU General Public License Version 2 or later (the "GPL"),
29 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
38 *
39 * ***** END LICENSE BLOCK ***** */
40
41#include "nsTimerImpl.h"
42#include "TimerThread.h"
43
44#include "nsAutoLock.h"
45#include "pratom.h"
46
47#include "nsIObserverService.h"
48#include "nsIServiceManager.h"
49
50NS_IMPL_THREADSAFE_ISUPPORTS3(TimerThread, nsIRunnable, nsISupportsWeakReference, nsIObserver)
51
52TimerThread::TimerThread() :
53 mInitInProgress(0),
54 mInitialized(PR_FALSE),
55 mLock(nsnull),
56 mCondVar(nsnull),
57 mShutdown(PR_FALSE),
58 mWaiting(PR_FALSE),
59 mSleeping(PR_FALSE),
60 mDelayLineCounter(0),
61 mMinTimerPeriod(0),
62 mTimeoutAdjustment(0)
63{
64}
65
66TimerThread::~TimerThread()
67{
68 if (mCondVar)
69 PR_DestroyCondVar(mCondVar);
70 if (mLock)
71 PR_DestroyLock(mLock);
72
73 mThread = nsnull;
74
75 PRInt32 n = mTimers.Count();
76 while (--n >= 0) {
77 nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[n]);
78 NS_RELEASE(timer);
79 }
80
81 nsCOMPtr<nsIObserverService> observerService = do_GetService("@mozilla.org/observer-service;1");
82 if (observerService) {
83 observerService->RemoveObserver(this, "sleep_notification");
84 observerService->RemoveObserver(this, "wake_notification");
85 }
86
87}
88
89nsresult
90TimerThread::InitLocks()
91{
92 NS_ASSERTION(!mLock, "InitLocks called twice?");
93 mLock = PR_NewLock();
94 if (!mLock)
95 return NS_ERROR_OUT_OF_MEMORY;
96
97 mCondVar = PR_NewCondVar(mLock);
98 if (!mCondVar)
99 return NS_ERROR_OUT_OF_MEMORY;
100
101 return NS_OK;
102}
103
104nsresult TimerThread::Init()
105{
106 if (mInitialized) {
107 if (!mThread)
108 return NS_ERROR_FAILURE;
109
110 return NS_OK;
111 }
112
113 if (PR_AtomicSet(&mInitInProgress, 1) == 0) {
114 nsresult rv;
115
116 mEventQueueService = do_GetService("@mozilla.org/event-queue-service;1", &rv);
117 if (NS_SUCCEEDED(rv)) {
118 nsCOMPtr<nsIObserverService> observerService
119 (do_GetService("@mozilla.org/observer-service;1", &rv));
120
121 if (NS_SUCCEEDED(rv)) {
122 // We hold on to mThread to keep the thread alive.
123 rv = NS_NewThread(getter_AddRefs(mThread),
124 NS_STATIC_CAST(nsIRunnable*, this),
125 0,
126 PR_JOINABLE_THREAD,
127 PR_PRIORITY_NORMAL,
128 PR_GLOBAL_THREAD);
129
130 if (NS_FAILED(rv)) {
131 mThread = nsnull;
132 }
133 else {
134 observerService->AddObserver(this, "sleep_notification", PR_TRUE);
135 observerService->AddObserver(this, "wake_notification", PR_TRUE);
136 }
137 }
138 }
139
140 PR_Lock(mLock);
141 mInitialized = PR_TRUE;
142 PR_NotifyAllCondVar(mCondVar);
143 PR_Unlock(mLock);
144 }
145 else {
146 PR_Lock(mLock);
147 while (!mInitialized) {
148 PR_WaitCondVar(mCondVar, PR_INTERVAL_NO_TIMEOUT);
149 }
150 PR_Unlock(mLock);
151 }
152
153 if (!mThread)
154 return NS_ERROR_FAILURE;
155
156 return NS_OK;
157}
158
159nsresult TimerThread::Shutdown()
160{
161 if (!mThread)
162 return NS_ERROR_NOT_INITIALIZED;
163
164 { // lock scope
165 nsAutoLock lock(mLock);
166
167 mShutdown = PR_TRUE;
168
169 // notify the cond var so that Run() can return
170 if (mCondVar && mWaiting)
171 PR_NotifyCondVar(mCondVar);
172
173 nsTimerImpl *timer;
174 for (PRInt32 i = mTimers.Count() - 1; i >= 0; i--) {
175 timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[i]);
176 RemoveTimerInternal(timer);
177 }
178 }
179
180 mThread->Join(); // wait for the thread to die
181 return NS_OK;
182}
183
184// Keep track of how early (positive slack) or late (negative slack) timers
185// are running, and use the filtered slack number to adaptively estimate how
186// early timers should fire to be "on time".
187void TimerThread::UpdateFilter(PRUint32 aDelay, PRIntervalTime aTimeout,
188 PRIntervalTime aNow)
189{
190 PRInt32 slack = (PRInt32) (aTimeout - aNow);
191 double smoothSlack = 0;
192 PRUint32 i, filterLength;
193 static PRIntervalTime kFilterFeedbackMaxTicks =
194 PR_MillisecondsToInterval(FILTER_FEEDBACK_MAX);
195
196 if (slack > 0) {
197 if (slack > (PRInt32)kFilterFeedbackMaxTicks)
198 slack = kFilterFeedbackMaxTicks;
199 } else {
200 if (slack < -(PRInt32)kFilterFeedbackMaxTicks)
201 slack = -(PRInt32)kFilterFeedbackMaxTicks;
202 }
203 mDelayLine[mDelayLineCounter & DELAY_LINE_LENGTH_MASK] = slack;
204 if (++mDelayLineCounter < DELAY_LINE_LENGTH) {
205 // Startup mode: accumulate a full delay line before filtering.
206 PR_ASSERT(mTimeoutAdjustment == 0);
207 filterLength = 0;
208 } else {
209 // Past startup: compute number of filter taps based on mMinTimerPeriod.
210 if (mMinTimerPeriod == 0) {
211 mMinTimerPeriod = (aDelay != 0) ? aDelay : 1;
212 } else if (aDelay != 0 && aDelay < mMinTimerPeriod) {
213 mMinTimerPeriod = aDelay;
214 }
215
216 filterLength = (PRUint32) (FILTER_DURATION / mMinTimerPeriod);
217 if (filterLength > DELAY_LINE_LENGTH)
218 filterLength = DELAY_LINE_LENGTH;
219 else if (filterLength < 4)
220 filterLength = 4;
221
222 for (i = 1; i <= filterLength; i++)
223 smoothSlack += mDelayLine[(mDelayLineCounter-i) & DELAY_LINE_LENGTH_MASK];
224 smoothSlack /= filterLength;
225
226 // XXXbe do we need amplification? hacking a fudge factor, need testing...
227 mTimeoutAdjustment = (PRInt32) (smoothSlack * 1.5);
228 }
229
230#ifdef DEBUG_TIMERS
231 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
232 PR_LOG(gTimerLog, PR_LOG_DEBUG,
233 ("UpdateFilter: smoothSlack = %g, filterLength = %u\n",
234 smoothSlack, filterLength));
235 }
236#endif
237}
238
239/* void Run(); */
240NS_IMETHODIMP TimerThread::Run()
241{
242 nsAutoLock lock(mLock);
243
244 while (!mShutdown) {
245 PRIntervalTime waitFor;
246
247 if (mSleeping) {
248 // Sleep for 0.1 seconds while not firing timers.
249 waitFor = PR_MillisecondsToInterval(100);
250 } else {
251 waitFor = PR_INTERVAL_NO_TIMEOUT;
252 PRIntervalTime now = PR_IntervalNow();
253 nsTimerImpl *timer = nsnull;
254
255 if (mTimers.Count() > 0) {
256 timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[0]);
257
258 if (!TIMER_LESS_THAN(now, timer->mTimeout + mTimeoutAdjustment)) {
259 next:
260 // NB: AddRef before the Release under RemoveTimerInternal to avoid
261 // mRefCnt passing through zero, in case all other refs than the one
262 // from mTimers have gone away (the last non-mTimers[i]-ref's Release
263 // must be racing with us, blocked in gThread->RemoveTimer waiting
264 // for TimerThread::mLock, under nsTimerImpl::Release.
265
266 NS_ADDREF(timer);
267 RemoveTimerInternal(timer);
268
269 // We release mLock around the Fire call to avoid deadlock.
270 lock.unlock();
271
272#ifdef DEBUG_TIMERS
273 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
274 PR_LOG(gTimerLog, PR_LOG_DEBUG,
275 ("Timer thread woke up %dms from when it was supposed to\n",
276 (now >= timer->mTimeout)
277 ? PR_IntervalToMilliseconds(now - timer->mTimeout)
278 : -(PRInt32)PR_IntervalToMilliseconds(timer->mTimeout-now))
279 );
280 }
281#endif
282
283 // We are going to let the call to PostTimerEvent here handle the
284 // release of the timer so that we don't end up releasing the timer
285 // on the TimerThread instead of on the thread it targets.
286 timer->PostTimerEvent();
287 timer = nsnull;
288
289 lock.lock();
290 if (mShutdown)
291 break;
292
293 // Update now, as PostTimerEvent plus the locking may have taken a
294 // tick or two, and we may goto next below.
295 now = PR_IntervalNow();
296 }
297 }
298
299 if (mTimers.Count() > 0) {
300 timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[0]);
301
302 PRIntervalTime timeout = timer->mTimeout + mTimeoutAdjustment;
303
304 // Don't wait at all (even for PR_INTERVAL_NO_WAIT) if the next timer
305 // is due now or overdue.
306 if (!TIMER_LESS_THAN(now, timeout))
307 goto next;
308 waitFor = timeout - now;
309 }
310
311#ifdef DEBUG_TIMERS
312 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
313 if (waitFor == PR_INTERVAL_NO_TIMEOUT)
314 PR_LOG(gTimerLog, PR_LOG_DEBUG,
315 ("waiting for PR_INTERVAL_NO_TIMEOUT\n"));
316 else
317 PR_LOG(gTimerLog, PR_LOG_DEBUG,
318 ("waiting for %u\n", PR_IntervalToMilliseconds(waitFor)));
319 }
320#endif
321 }
322
323 mWaiting = PR_TRUE;
324 PR_WaitCondVar(mCondVar, waitFor);
325 mWaiting = PR_FALSE;
326 }
327
328 return NS_OK;
329}
330
331nsresult TimerThread::AddTimer(nsTimerImpl *aTimer)
332{
333 nsAutoLock lock(mLock);
334
335 // Add the timer to our list.
336 PRInt32 i = AddTimerInternal(aTimer);
337 if (i < 0)
338 return NS_ERROR_OUT_OF_MEMORY;
339
340 // Awaken the timer thread.
341 if (mCondVar && mWaiting && i == 0)
342 PR_NotifyCondVar(mCondVar);
343
344 return NS_OK;
345}
346
347nsresult TimerThread::TimerDelayChanged(nsTimerImpl *aTimer)
348{
349 nsAutoLock lock(mLock);
350
351 // Our caller has a strong ref to aTimer, so it can't go away here under
352 // ReleaseTimerInternal.
353 RemoveTimerInternal(aTimer);
354
355 PRInt32 i = AddTimerInternal(aTimer);
356 if (i < 0)
357 return NS_ERROR_OUT_OF_MEMORY;
358
359 // Awaken the timer thread.
360 if (mCondVar && mWaiting && i == 0)
361 PR_NotifyCondVar(mCondVar);
362
363 return NS_OK;
364}
365
366nsresult TimerThread::RemoveTimer(nsTimerImpl *aTimer)
367{
368 nsAutoLock lock(mLock);
369
370 // Remove the timer from our array. Tell callers that aTimer was not found
371 // by returning NS_ERROR_NOT_AVAILABLE. Unlike the TimerDelayChanged case
372 // immediately above, our caller may be passing a (now-)weak ref in via the
373 // aTimer param, specifically when nsTimerImpl::Release loses a race with
374 // TimerThread::Run, must wait for the mLock auto-lock here, and during the
375 // wait Run drops the only remaining ref to aTimer via RemoveTimerInternal.
376
377 if (!RemoveTimerInternal(aTimer))
378 return NS_ERROR_NOT_AVAILABLE;
379
380 // Awaken the timer thread.
381 if (mCondVar && mWaiting)
382 PR_NotifyCondVar(mCondVar);
383
384 return NS_OK;
385}
386
387// This function must be called from within a lock
388PRInt32 TimerThread::AddTimerInternal(nsTimerImpl *aTimer)
389{
390 PRIntervalTime now = PR_IntervalNow();
391 PRInt32 count = mTimers.Count();
392 PRInt32 i = 0;
393 for (; i < count; i++) {
394 nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[i]);
395
396 // Don't break till we have skipped any overdue timers. Do not include
397 // mTimeoutAdjustment here, because we are really trying to avoid calling
398 // TIMER_LESS_THAN(t, u), where the t is now + DELAY_INTERVAL_MAX, u is
399 // now - overdue, and DELAY_INTERVAL_MAX + overdue > DELAY_INTERVAL_LIMIT.
400 // In other words, we want to use now-based time, now adjusted time, even
401 // though "overdue" ultimately depends on adjusted time.
402
403 // XXX does this hold for TYPE_REPEATING_PRECISE? /be
404
405 if (TIMER_LESS_THAN(now, timer->mTimeout) &&
406 TIMER_LESS_THAN(aTimer->mTimeout, timer->mTimeout)) {
407 break;
408 }
409 }
410
411 if (!mTimers.InsertElementAt(aTimer, i))
412 return -1;
413
414 aTimer->mArmed = PR_TRUE;
415 NS_ADDREF(aTimer);
416 return i;
417}
418
419PRBool TimerThread::RemoveTimerInternal(nsTimerImpl *aTimer)
420{
421 if (!mTimers.RemoveElement(aTimer))
422 return PR_FALSE;
423
424 // Order is crucial here -- see nsTimerImpl::Release.
425 aTimer->mArmed = PR_FALSE;
426 NS_RELEASE(aTimer);
427 return PR_TRUE;
428}
429
430void TimerThread::DoBeforeSleep()
431{
432 mSleeping = PR_TRUE;
433}
434
435void TimerThread::DoAfterSleep()
436{
437 for (PRInt32 i = 0; i < mTimers.Count(); i ++) {
438 nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[i]);
439 // get and set the delay to cause its timeout to be recomputed
440 PRUint32 delay;
441 timer->GetDelay(&delay);
442 timer->SetDelay(delay);
443 }
444
445 // nuke the stored adjustments, so they get recalibrated
446 mTimeoutAdjustment = 0;
447 mDelayLineCounter = 0;
448 mSleeping = PR_FALSE;
449}
450
451
452/* void observe (in nsISupports aSubject, in string aTopic, in wstring aData); */
453NS_IMETHODIMP
454TimerThread::Observe(nsISupports* /* aSubject */, const char *aTopic, const PRUnichar* /* aData */)
455{
456 if (strcmp(aTopic, "sleep_notification") == 0)
457 DoBeforeSleep();
458 else if (strcmp(aTopic, "wake_notification") == 0)
459 DoAfterSleep();
460
461 return NS_OK;
462}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette