Timer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /*
  2. * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
  3. * Copyright (C) 2009 Google Inc. All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  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.
  13. *
  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.
  25. */
  26. #include "config.h"
  27. #include "Timer.h"
  28. #include "SharedTimer.h"
  29. #include "ThreadGlobalData.h"
  30. #include "ThreadTimers.h"
  31. #include <limits.h>
  32. #include <limits>
  33. #include <math.h>
  34. #include <wtf/CurrentTime.h>
  35. #include <wtf/HashSet.h>
  36. #include <wtf/Vector.h>
  37. using namespace std;
  38. namespace WebCore {
  39. class TimerHeapReference;
  40. // Timers are stored in a heap data structure, used to implement a priority queue.
  41. // This allows us to efficiently determine which timer needs to fire the soonest.
  42. // Then we set a single shared system timer to fire at that time.
  43. //
  44. // When a timer's "next fire time" changes, we need to move it around in the priority queue.
  45. static Vector<TimerBase*>& threadGlobalTimerHeap()
  46. {
  47. return threadGlobalData().threadTimers().timerHeap();
  48. }
  49. // ----------------
  50. class TimerHeapPointer {
  51. public:
  52. TimerHeapPointer(TimerBase** pointer) : m_pointer(pointer) { }
  53. TimerHeapReference operator*() const;
  54. TimerBase* operator->() const { return *m_pointer; }
  55. private:
  56. TimerBase** m_pointer;
  57. };
  58. class TimerHeapReference {
  59. public:
  60. TimerHeapReference(TimerBase*& reference) : m_reference(reference) { }
  61. operator TimerBase*() const { return m_reference; }
  62. TimerHeapPointer operator&() const { return &m_reference; }
  63. TimerHeapReference& operator=(TimerBase*);
  64. TimerHeapReference& operator=(TimerHeapReference);
  65. private:
  66. TimerBase*& m_reference;
  67. };
  68. inline TimerHeapReference TimerHeapPointer::operator*() const
  69. {
  70. return *m_pointer;
  71. }
  72. inline TimerHeapReference& TimerHeapReference::operator=(TimerBase* timer)
  73. {
  74. m_reference = timer;
  75. Vector<TimerBase*>& heap = timer->timerHeap();
  76. if (&m_reference >= heap.data() && &m_reference < heap.data() + heap.size())
  77. timer->m_heapIndex = &m_reference - heap.data();
  78. return *this;
  79. }
  80. inline TimerHeapReference& TimerHeapReference::operator=(TimerHeapReference b)
  81. {
  82. TimerBase* timer = b;
  83. return *this = timer;
  84. }
  85. inline void swap(TimerHeapReference a, TimerHeapReference b)
  86. {
  87. TimerBase* timerA = a;
  88. TimerBase* timerB = b;
  89. // Invoke the assignment operator, since that takes care of updating m_heapIndex.
  90. a = timerB;
  91. b = timerA;
  92. }
  93. // ----------------
  94. // Class to represent iterators in the heap when calling the standard library heap algorithms.
  95. // Uses a custom pointer and reference type that update indices for pointers in the heap.
  96. class TimerHeapIterator : public iterator<random_access_iterator_tag, TimerBase*, ptrdiff_t, TimerHeapPointer, TimerHeapReference> {
  97. public:
  98. explicit TimerHeapIterator(TimerBase** pointer) : m_pointer(pointer) { checkConsistency(); }
  99. TimerHeapIterator& operator++() { checkConsistency(); ++m_pointer; checkConsistency(); return *this; }
  100. TimerHeapIterator operator++(int) { checkConsistency(1); return TimerHeapIterator(m_pointer++); }
  101. TimerHeapIterator& operator--() { checkConsistency(); --m_pointer; checkConsistency(); return *this; }
  102. TimerHeapIterator operator--(int) { checkConsistency(-1); return TimerHeapIterator(m_pointer--); }
  103. TimerHeapIterator& operator+=(ptrdiff_t i) { checkConsistency(); m_pointer += i; checkConsistency(); return *this; }
  104. TimerHeapIterator& operator-=(ptrdiff_t i) { checkConsistency(); m_pointer -= i; checkConsistency(); return *this; }
  105. TimerHeapReference operator*() const { return TimerHeapReference(*m_pointer); }
  106. TimerHeapReference operator[](ptrdiff_t i) const { return TimerHeapReference(m_pointer[i]); }
  107. TimerBase* operator->() const { return *m_pointer; }
  108. private:
  109. void checkConsistency(ptrdiff_t offset = 0) const
  110. {
  111. ASSERT(m_pointer >= threadGlobalTimerHeap().data());
  112. ASSERT(m_pointer <= threadGlobalTimerHeap().data() + threadGlobalTimerHeap().size());
  113. ASSERT_UNUSED(offset, m_pointer + offset >= threadGlobalTimerHeap().data());
  114. ASSERT_UNUSED(offset, m_pointer + offset <= threadGlobalTimerHeap().data() + threadGlobalTimerHeap().size());
  115. }
  116. friend bool operator==(TimerHeapIterator, TimerHeapIterator);
  117. friend bool operator!=(TimerHeapIterator, TimerHeapIterator);
  118. friend bool operator<(TimerHeapIterator, TimerHeapIterator);
  119. friend bool operator>(TimerHeapIterator, TimerHeapIterator);
  120. friend bool operator<=(TimerHeapIterator, TimerHeapIterator);
  121. friend bool operator>=(TimerHeapIterator, TimerHeapIterator);
  122. friend TimerHeapIterator operator+(TimerHeapIterator, size_t);
  123. friend TimerHeapIterator operator+(size_t, TimerHeapIterator);
  124. friend TimerHeapIterator operator-(TimerHeapIterator, size_t);
  125. friend ptrdiff_t operator-(TimerHeapIterator, TimerHeapIterator);
  126. TimerBase** m_pointer;
  127. };
  128. inline bool operator==(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer == b.m_pointer; }
  129. inline bool operator!=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer != b.m_pointer; }
  130. inline bool operator<(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer < b.m_pointer; }
  131. inline bool operator>(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer > b.m_pointer; }
  132. inline bool operator<=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer <= b.m_pointer; }
  133. inline bool operator>=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer >= b.m_pointer; }
  134. inline TimerHeapIterator operator+(TimerHeapIterator a, size_t b) { return TimerHeapIterator(a.m_pointer + b); }
  135. inline TimerHeapIterator operator+(size_t a, TimerHeapIterator b) { return TimerHeapIterator(a + b.m_pointer); }
  136. inline TimerHeapIterator operator-(TimerHeapIterator a, size_t b) { return TimerHeapIterator(a.m_pointer - b); }
  137. inline ptrdiff_t operator-(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer - b.m_pointer; }
  138. // ----------------
  139. class TimerHeapLessThanFunction {
  140. public:
  141. bool operator()(const TimerBase*, const TimerBase*) const;
  142. };
  143. inline bool TimerHeapLessThanFunction::operator()(const TimerBase* a, const TimerBase* b) const
  144. {
  145. // The comparisons below are "backwards" because the heap puts the largest
  146. // element first and we want the lowest time to be the first one in the heap.
  147. double aFireTime = a->m_nextFireTime;
  148. double bFireTime = b->m_nextFireTime;
  149. if (bFireTime != aFireTime)
  150. return bFireTime < aFireTime;
  151. // We need to look at the difference of the insertion orders instead of comparing the two
  152. // outright in case of overflow.
  153. unsigned difference = a->m_heapInsertionOrder - b->m_heapInsertionOrder;
  154. return difference < numeric_limits<unsigned>::max() / 2;
  155. }
  156. // ----------------
  157. TimerBase::TimerBase()
  158. : m_nextFireTime(0)
  159. , m_unalignedNextFireTime(0)
  160. , m_repeatInterval(0)
  161. , m_heapIndex(-1)
  162. , m_cachedThreadGlobalTimerHeap(0)
  163. #ifndef NDEBUG
  164. , m_thread(currentThread())
  165. #endif
  166. {
  167. }
  168. TimerBase::~TimerBase()
  169. {
  170. stop();
  171. ASSERT(!inHeap());
  172. }
  173. void TimerBase::start(double nextFireInterval, double repeatInterval)
  174. {
  175. ASSERT(m_thread == currentThread());
  176. m_repeatInterval = repeatInterval;
  177. setNextFireTime(monotonicallyIncreasingTime() + nextFireInterval);
  178. }
  179. void TimerBase::stop()
  180. {
  181. ASSERT(m_thread == currentThread());
  182. m_repeatInterval = 0;
  183. setNextFireTime(0);
  184. ASSERT(m_nextFireTime == 0);
  185. ASSERT(m_repeatInterval == 0);
  186. ASSERT(!inHeap());
  187. }
  188. double TimerBase::nextFireInterval() const
  189. {
  190. ASSERT(isActive());
  191. double current = monotonicallyIncreasingTime();
  192. if (m_nextFireTime < current)
  193. return 0;
  194. return m_nextFireTime - current;
  195. }
  196. inline void TimerBase::checkHeapIndex() const
  197. {
  198. ASSERT(timerHeap() == threadGlobalTimerHeap());
  199. ASSERT(!timerHeap().isEmpty());
  200. ASSERT(m_heapIndex >= 0);
  201. ASSERT(m_heapIndex < static_cast<int>(timerHeap().size()));
  202. ASSERT(timerHeap()[m_heapIndex] == this);
  203. }
  204. inline void TimerBase::checkConsistency() const
  205. {
  206. // Timers should be in the heap if and only if they have a non-zero next fire time.
  207. ASSERT(inHeap() == (m_nextFireTime != 0));
  208. if (inHeap())
  209. checkHeapIndex();
  210. }
  211. void TimerBase::heapDecreaseKey()
  212. {
  213. ASSERT(m_nextFireTime != 0);
  214. checkHeapIndex();
  215. TimerBase** heapData = timerHeap().data();
  216. push_heap(TimerHeapIterator(heapData), TimerHeapIterator(heapData + m_heapIndex + 1), TimerHeapLessThanFunction());
  217. checkHeapIndex();
  218. }
  219. inline void TimerBase::heapDelete()
  220. {
  221. ASSERT(m_nextFireTime == 0);
  222. heapPop();
  223. timerHeap().removeLast();
  224. m_heapIndex = -1;
  225. }
  226. void TimerBase::heapDeleteMin()
  227. {
  228. ASSERT(m_nextFireTime == 0);
  229. heapPopMin();
  230. timerHeap().removeLast();
  231. m_heapIndex = -1;
  232. }
  233. inline void TimerBase::heapIncreaseKey()
  234. {
  235. ASSERT(m_nextFireTime != 0);
  236. heapPop();
  237. heapDecreaseKey();
  238. }
  239. inline void TimerBase::heapInsert()
  240. {
  241. ASSERT(!inHeap());
  242. timerHeap().append(this);
  243. m_heapIndex = timerHeap().size() - 1;
  244. heapDecreaseKey();
  245. }
  246. inline void TimerBase::heapPop()
  247. {
  248. // Temporarily force this timer to have the minimum key so we can pop it.
  249. double fireTime = m_nextFireTime;
  250. m_nextFireTime = -numeric_limits<double>::infinity();
  251. heapDecreaseKey();
  252. heapPopMin();
  253. m_nextFireTime = fireTime;
  254. }
  255. void TimerBase::heapPopMin()
  256. {
  257. ASSERT(this == timerHeap().first());
  258. checkHeapIndex();
  259. Vector<TimerBase*>& heap = timerHeap();
  260. TimerBase** heapData = heap.data();
  261. pop_heap(TimerHeapIterator(heapData), TimerHeapIterator(heapData + heap.size()), TimerHeapLessThanFunction());
  262. checkHeapIndex();
  263. ASSERT(this == timerHeap().last());
  264. }
  265. static inline bool parentHeapPropertyHolds(const TimerBase* current, const Vector<TimerBase*>& heap, unsigned currentIndex)
  266. {
  267. if (!currentIndex)
  268. return true;
  269. unsigned parentIndex = (currentIndex - 1) / 2;
  270. TimerHeapLessThanFunction compareHeapPosition;
  271. return compareHeapPosition(current, heap[parentIndex]);
  272. }
  273. static inline bool childHeapPropertyHolds(const TimerBase* current, const Vector<TimerBase*>& heap, unsigned childIndex)
  274. {
  275. if (childIndex >= heap.size())
  276. return true;
  277. TimerHeapLessThanFunction compareHeapPosition;
  278. return compareHeapPosition(heap[childIndex], current);
  279. }
  280. bool TimerBase::hasValidHeapPosition() const
  281. {
  282. ASSERT(m_nextFireTime);
  283. if (!inHeap())
  284. return false;
  285. // Check if the heap property still holds with the new fire time. If it does we don't need to do anything.
  286. // This assumes that the STL heap is a standard binary heap. In an unlikely event it is not, the assertions
  287. // in updateHeapIfNeeded() will get hit.
  288. const Vector<TimerBase*>& heap = timerHeap();
  289. if (!parentHeapPropertyHolds(this, heap, m_heapIndex))
  290. return false;
  291. unsigned childIndex1 = 2 * m_heapIndex + 1;
  292. unsigned childIndex2 = childIndex1 + 1;
  293. return childHeapPropertyHolds(this, heap, childIndex1) && childHeapPropertyHolds(this, heap, childIndex2);
  294. }
  295. void TimerBase::updateHeapIfNeeded(double oldTime)
  296. {
  297. if (m_nextFireTime && hasValidHeapPosition())
  298. return;
  299. #ifndef NDEBUG
  300. int oldHeapIndex = m_heapIndex;
  301. #endif
  302. if (!oldTime)
  303. heapInsert();
  304. else if (!m_nextFireTime)
  305. heapDelete();
  306. else if (m_nextFireTime < oldTime)
  307. heapDecreaseKey();
  308. else
  309. heapIncreaseKey();
  310. ASSERT(m_heapIndex != oldHeapIndex);
  311. ASSERT(!inHeap() || hasValidHeapPosition());
  312. }
  313. void TimerBase::setNextFireTime(double newUnalignedTime)
  314. {
  315. ASSERT(m_thread == currentThread());
  316. if (m_unalignedNextFireTime != newUnalignedTime)
  317. m_unalignedNextFireTime = newUnalignedTime;
  318. // Accessing thread global data is slow. Cache the heap pointer.
  319. if (!m_cachedThreadGlobalTimerHeap)
  320. m_cachedThreadGlobalTimerHeap = &threadGlobalTimerHeap();
  321. // Keep heap valid while changing the next-fire time.
  322. double oldTime = m_nextFireTime;
  323. double newTime = alignedFireTime(newUnalignedTime);
  324. if (oldTime != newTime) {
  325. m_nextFireTime = newTime;
  326. static unsigned currentHeapInsertionOrder;
  327. m_heapInsertionOrder = currentHeapInsertionOrder++;
  328. bool wasFirstTimerInHeap = m_heapIndex == 0;
  329. updateHeapIfNeeded(oldTime);
  330. bool isFirstTimerInHeap = m_heapIndex == 0;
  331. if (wasFirstTimerInHeap || isFirstTimerInHeap)
  332. threadGlobalData().threadTimers().updateSharedTimer();
  333. }
  334. checkConsistency();
  335. }
  336. void TimerBase::fireTimersInNestedEventLoop()
  337. {
  338. // Redirect to ThreadTimers.
  339. threadGlobalData().threadTimers().fireTimersInNestedEventLoop();
  340. }
  341. void TimerBase::didChangeAlignmentInterval()
  342. {
  343. setNextFireTime(m_unalignedNextFireTime);
  344. }
  345. double TimerBase::nextUnalignedFireInterval() const
  346. {
  347. ASSERT(isActive());
  348. return max(m_unalignedNextFireTime - monotonicallyIncreasingTime(), 0.0);
  349. }
  350. } // namespace WebCore