2 * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2009 Google Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "platform/Timer.h"
30 #include "platform/PlatformThreadData.h"
31 #include "platform/ThreadTimers.h"
32 #include "wtf/CurrentTime.h"
33 #include "wtf/HashSet.h"
42 class TimerHeapReference;
44 // Timers are stored in a heap data structure, used to implement a priority queue.
45 // This allows us to efficiently determine which timer needs to fire the soonest.
46 // Then we set a single shared system timer to fire at that time.
48 // When a timer's "next fire time" changes, we need to move it around in the priority queue.
49 static Vector<TimerBase*>& threadGlobalTimerHeap()
51 return PlatformThreadData::current().threadTimers().timerHeap();
55 class TimerHeapPointer {
57 TimerHeapPointer(TimerBase** pointer) : m_pointer(pointer) { }
58 TimerHeapReference operator*() const;
59 TimerBase* operator->() const { return *m_pointer; }
61 TimerBase** m_pointer;
64 class TimerHeapReference {
66 TimerHeapReference(TimerBase*& reference) : m_reference(reference) { }
67 operator TimerBase*() const { return m_reference; }
68 TimerHeapPointer operator&() const { return &m_reference; }
69 TimerHeapReference& operator=(TimerBase*);
70 TimerHeapReference& operator=(TimerHeapReference);
72 TimerBase*& m_reference;
75 inline TimerHeapReference TimerHeapPointer::operator*() const
80 inline TimerHeapReference& TimerHeapReference::operator=(TimerBase* timer)
83 Vector<TimerBase*>& heap = timer->timerHeap();
84 if (&m_reference >= heap.data() && &m_reference < heap.data() + heap.size())
85 timer->m_heapIndex = &m_reference - heap.data();
89 inline TimerHeapReference& TimerHeapReference::operator=(TimerHeapReference b)
95 inline void swap(TimerHeapReference a, TimerHeapReference b)
97 TimerBase* timerA = a;
98 TimerBase* timerB = b;
100 // Invoke the assignment operator, since that takes care of updating m_heapIndex.
107 // Class to represent iterators in the heap when calling the standard library heap algorithms.
108 // Uses a custom pointer and reference type that update indices for pointers in the heap.
109 class TimerHeapIterator : public iterator<random_access_iterator_tag, TimerBase*, ptrdiff_t, TimerHeapPointer, TimerHeapReference> {
111 explicit TimerHeapIterator(TimerBase** pointer) : m_pointer(pointer) { checkConsistency(); }
113 TimerHeapIterator& operator++() { checkConsistency(); ++m_pointer; checkConsistency(); return *this; }
114 TimerHeapIterator operator++(int) { checkConsistency(1); return TimerHeapIterator(m_pointer++); }
116 TimerHeapIterator& operator--() { checkConsistency(); --m_pointer; checkConsistency(); return *this; }
117 TimerHeapIterator operator--(int) { checkConsistency(-1); return TimerHeapIterator(m_pointer--); }
119 TimerHeapIterator& operator+=(ptrdiff_t i) { checkConsistency(); m_pointer += i; checkConsistency(); return *this; }
120 TimerHeapIterator& operator-=(ptrdiff_t i) { checkConsistency(); m_pointer -= i; checkConsistency(); return *this; }
122 TimerHeapReference operator*() const { return TimerHeapReference(*m_pointer); }
123 TimerHeapReference operator[](ptrdiff_t i) const { return TimerHeapReference(m_pointer[i]); }
124 TimerBase* operator->() const { return *m_pointer; }
127 void checkConsistency(ptrdiff_t offset = 0) const
129 ASSERT(m_pointer >= threadGlobalTimerHeap().data());
130 ASSERT(m_pointer <= threadGlobalTimerHeap().data() + threadGlobalTimerHeap().size());
131 ASSERT_UNUSED(offset, m_pointer + offset >= threadGlobalTimerHeap().data());
132 ASSERT_UNUSED(offset, m_pointer + offset <= threadGlobalTimerHeap().data() + threadGlobalTimerHeap().size());
135 friend bool operator==(TimerHeapIterator, TimerHeapIterator);
136 friend bool operator!=(TimerHeapIterator, TimerHeapIterator);
137 friend bool operator<(TimerHeapIterator, TimerHeapIterator);
138 friend bool operator>(TimerHeapIterator, TimerHeapIterator);
139 friend bool operator<=(TimerHeapIterator, TimerHeapIterator);
140 friend bool operator>=(TimerHeapIterator, TimerHeapIterator);
142 friend TimerHeapIterator operator+(TimerHeapIterator, size_t);
143 friend TimerHeapIterator operator+(size_t, TimerHeapIterator);
145 friend TimerHeapIterator operator-(TimerHeapIterator, size_t);
146 friend ptrdiff_t operator-(TimerHeapIterator, TimerHeapIterator);
148 TimerBase** m_pointer;
151 inline bool operator==(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer == b.m_pointer; }
152 inline bool operator!=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer != b.m_pointer; }
153 inline bool operator<(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer < b.m_pointer; }
154 inline bool operator>(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer > b.m_pointer; }
155 inline bool operator<=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer <= b.m_pointer; }
156 inline bool operator>=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer >= b.m_pointer; }
158 inline TimerHeapIterator operator+(TimerHeapIterator a, size_t b) { return TimerHeapIterator(a.m_pointer + b); }
159 inline TimerHeapIterator operator+(size_t a, TimerHeapIterator b) { return TimerHeapIterator(a + b.m_pointer); }
161 inline TimerHeapIterator operator-(TimerHeapIterator a, size_t b) { return TimerHeapIterator(a.m_pointer - b); }
162 inline ptrdiff_t operator-(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer - b.m_pointer; }
166 class TimerHeapLessThanFunction {
168 bool operator()(const TimerBase*, const TimerBase*) const;
171 inline bool TimerHeapLessThanFunction::operator()(const TimerBase* a, const TimerBase* b) const
173 // The comparisons below are "backwards" because the heap puts the largest
174 // element first and we want the lowest time to be the first one in the heap.
175 double aFireTime = a->m_nextFireTime;
176 double bFireTime = b->m_nextFireTime;
177 if (bFireTime != aFireTime)
178 return bFireTime < aFireTime;
180 // We need to look at the difference of the insertion orders instead of comparing the two
181 // outright in case of overflow.
182 unsigned difference = a->m_heapInsertionOrder - b->m_heapInsertionOrder;
183 return difference < numeric_limits<unsigned>::max() / 2;
188 TimerBase::TimerBase()
190 , m_unalignedNextFireTime(0)
191 , m_repeatInterval(0)
193 , m_cachedThreadGlobalTimerHeap(0)
195 , m_thread(currentThread())
200 TimerBase::~TimerBase()
206 void TimerBase::start(double nextFireInterval, double repeatInterval)
208 ASSERT(m_thread == currentThread());
210 m_repeatInterval = repeatInterval;
211 setNextFireTime(monotonicallyIncreasingTime() + nextFireInterval);
214 void TimerBase::stop()
216 ASSERT(m_thread == currentThread());
218 m_repeatInterval = 0;
221 ASSERT(m_nextFireTime == 0);
222 ASSERT(m_repeatInterval == 0);
226 double TimerBase::nextFireInterval() const
229 double current = monotonicallyIncreasingTime();
230 if (m_nextFireTime < current)
232 return m_nextFireTime - current;
235 inline void TimerBase::checkHeapIndex() const
237 ASSERT(timerHeap() == threadGlobalTimerHeap());
238 ASSERT(!timerHeap().isEmpty());
239 ASSERT(m_heapIndex >= 0);
240 ASSERT(m_heapIndex < static_cast<int>(timerHeap().size()));
241 ASSERT(timerHeap()[m_heapIndex] == this);
244 inline void TimerBase::checkConsistency() const
246 // Timers should be in the heap if and only if they have a non-zero next fire time.
247 ASSERT(inHeap() == (m_nextFireTime != 0));
252 void TimerBase::heapDecreaseKey()
254 ASSERT(m_nextFireTime != 0);
256 TimerBase** heapData = timerHeap().data();
257 push_heap(TimerHeapIterator(heapData), TimerHeapIterator(heapData + m_heapIndex + 1), TimerHeapLessThanFunction());
261 inline void TimerBase::heapDelete()
263 ASSERT(m_nextFireTime == 0);
265 timerHeap().removeLast();
269 void TimerBase::heapDeleteMin()
271 ASSERT(m_nextFireTime == 0);
273 timerHeap().removeLast();
277 inline void TimerBase::heapIncreaseKey()
279 ASSERT(m_nextFireTime != 0);
284 inline void TimerBase::heapInsert()
287 timerHeap().append(this);
288 m_heapIndex = timerHeap().size() - 1;
292 inline void TimerBase::heapPop()
294 // Temporarily force this timer to have the minimum key so we can pop it.
295 double fireTime = m_nextFireTime;
296 m_nextFireTime = -numeric_limits<double>::infinity();
299 m_nextFireTime = fireTime;
302 void TimerBase::heapPopMin()
304 ASSERT(this == timerHeap().first());
306 Vector<TimerBase*>& heap = timerHeap();
307 TimerBase** heapData = heap.data();
308 pop_heap(TimerHeapIterator(heapData), TimerHeapIterator(heapData + heap.size()), TimerHeapLessThanFunction());
310 ASSERT(this == timerHeap().last());
313 static inline bool parentHeapPropertyHolds(const TimerBase* current, const Vector<TimerBase*>& heap, unsigned currentIndex)
317 unsigned parentIndex = (currentIndex - 1) / 2;
318 TimerHeapLessThanFunction compareHeapPosition;
319 return compareHeapPosition(current, heap[parentIndex]);
322 static inline bool childHeapPropertyHolds(const TimerBase* current, const Vector<TimerBase*>& heap, unsigned childIndex)
324 if (childIndex >= heap.size())
326 TimerHeapLessThanFunction compareHeapPosition;
327 return compareHeapPosition(heap[childIndex], current);
330 bool TimerBase::hasValidHeapPosition() const
332 ASSERT(m_nextFireTime);
335 // Check if the heap property still holds with the new fire time. If it does we don't need to do anything.
336 // This assumes that the STL heap is a standard binary heap. In an unlikely event it is not, the assertions
337 // in updateHeapIfNeeded() will get hit.
338 const Vector<TimerBase*>& heap = timerHeap();
339 if (!parentHeapPropertyHolds(this, heap, m_heapIndex))
341 unsigned childIndex1 = 2 * m_heapIndex + 1;
342 unsigned childIndex2 = childIndex1 + 1;
343 return childHeapPropertyHolds(this, heap, childIndex1) && childHeapPropertyHolds(this, heap, childIndex2);
346 void TimerBase::updateHeapIfNeeded(double oldTime)
348 if (m_nextFireTime && hasValidHeapPosition())
351 int oldHeapIndex = m_heapIndex;
355 else if (!m_nextFireTime)
357 else if (m_nextFireTime < oldTime)
361 ASSERT(m_heapIndex != oldHeapIndex);
362 ASSERT(!inHeap() || hasValidHeapPosition());
365 void TimerBase::setNextFireTime(double newUnalignedTime)
367 ASSERT(m_thread == currentThread());
369 if (m_unalignedNextFireTime != newUnalignedTime)
370 m_unalignedNextFireTime = newUnalignedTime;
372 // Accessing thread global data is slow. Cache the heap pointer.
373 if (!m_cachedThreadGlobalTimerHeap)
374 m_cachedThreadGlobalTimerHeap = &threadGlobalTimerHeap();
376 // Keep heap valid while changing the next-fire time.
377 double oldTime = m_nextFireTime;
378 double newTime = alignedFireTime(newUnalignedTime);
379 if (oldTime != newTime) {
380 m_nextFireTime = newTime;
381 static unsigned currentHeapInsertionOrder;
382 m_heapInsertionOrder = currentHeapInsertionOrder++;
384 bool wasFirstTimerInHeap = m_heapIndex == 0;
386 updateHeapIfNeeded(oldTime);
388 bool isFirstTimerInHeap = m_heapIndex == 0;
390 if (wasFirstTimerInHeap || isFirstTimerInHeap)
391 PlatformThreadData::current().threadTimers().updateSharedTimer();
397 void TimerBase::fireTimersInNestedEventLoop()
399 // Redirect to ThreadTimers.
400 PlatformThreadData::current().threadTimers().fireTimersInNestedEventLoop();
403 void TimerBase::didChangeAlignmentInterval()
405 setNextFireTime(m_unalignedNextFireTime);
408 double TimerBase::nextUnalignedFireInterval() const
411 return max(m_unalignedNextFireTime - monotonicallyIncreasingTime(), 0.0);
414 } // namespace WebCore