MainThread.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*
  2. * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  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. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
  14. * its contributors may be used to endorse or promote products derived
  15. * from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
  18. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  21. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #include "config.h"
  29. #include "MainThread.h"
  30. #include "CurrentTime.h"
  31. #include "Deque.h"
  32. #include "Functional.h"
  33. #include "StdLibExtras.h"
  34. #include "Threading.h"
  35. #include <wtf/ThreadSpecific.h>
  36. namespace WTF {
  37. struct FunctionWithContext {
  38. MainThreadFunction* function;
  39. void* context;
  40. ThreadCondition* syncFlag;
  41. FunctionWithContext(MainThreadFunction* function = 0, void* context = 0, ThreadCondition* syncFlag = 0)
  42. : function(function)
  43. , context(context)
  44. , syncFlag(syncFlag)
  45. {
  46. }
  47. bool operator == (const FunctionWithContext& o)
  48. {
  49. return function == o.function
  50. && context == o.context
  51. && syncFlag == o.syncFlag;
  52. }
  53. };
  54. class FunctionWithContextFinder {
  55. public:
  56. FunctionWithContextFinder(const FunctionWithContext& m) : m(m) {}
  57. bool operator() (FunctionWithContext& o) { return o == m; }
  58. FunctionWithContext m;
  59. };
  60. typedef Deque<FunctionWithContext> FunctionQueue;
  61. static bool callbacksPaused; // This global variable is only accessed from main thread.
  62. #if !PLATFORM(MAC)
  63. static ThreadIdentifier mainThreadIdentifier;
  64. #endif
  65. static Mutex& mainThreadFunctionQueueMutex()
  66. {
  67. DEFINE_STATIC_LOCAL(Mutex, staticMutex, ());
  68. return staticMutex;
  69. }
  70. static FunctionQueue& functionQueue()
  71. {
  72. DEFINE_STATIC_LOCAL(FunctionQueue, staticFunctionQueue, ());
  73. return staticFunctionQueue;
  74. }
  75. #if !PLATFORM(MAC)
  76. void initializeMainThread()
  77. {
  78. static bool initializedMainThread;
  79. if (initializedMainThread)
  80. return;
  81. initializedMainThread = true;
  82. mainThreadIdentifier = currentThread();
  83. mainThreadFunctionQueueMutex();
  84. initializeMainThreadPlatform();
  85. initializeGCThreads();
  86. }
  87. #else
  88. static pthread_once_t initializeMainThreadKeyOnce = PTHREAD_ONCE_INIT;
  89. static void initializeMainThreadOnce()
  90. {
  91. mainThreadFunctionQueueMutex();
  92. initializeMainThreadPlatform();
  93. }
  94. void initializeMainThread()
  95. {
  96. pthread_once(&initializeMainThreadKeyOnce, initializeMainThreadOnce);
  97. }
  98. #if !USE(WEB_THREAD)
  99. static void initializeMainThreadToProcessMainThreadOnce()
  100. {
  101. mainThreadFunctionQueueMutex();
  102. initializeMainThreadToProcessMainThreadPlatform();
  103. }
  104. void initializeMainThreadToProcessMainThread()
  105. {
  106. pthread_once(&initializeMainThreadKeyOnce, initializeMainThreadToProcessMainThreadOnce);
  107. }
  108. #endif // !USE(WEB_THREAD)
  109. #endif
  110. // 0.1 sec delays in UI is approximate threshold when they become noticeable. Have a limit that's half of that.
  111. static const double maxRunLoopSuspensionTime = 0.05;
  112. void dispatchFunctionsFromMainThread()
  113. {
  114. ASSERT(isMainThread());
  115. if (callbacksPaused)
  116. return;
  117. double startTime = currentTime();
  118. FunctionWithContext invocation;
  119. while (true) {
  120. {
  121. MutexLocker locker(mainThreadFunctionQueueMutex());
  122. if (!functionQueue().size())
  123. break;
  124. invocation = functionQueue().takeFirst();
  125. }
  126. invocation.function(invocation.context);
  127. if (invocation.syncFlag) {
  128. MutexLocker locker(mainThreadFunctionQueueMutex());
  129. invocation.syncFlag->signal();
  130. }
  131. // If we are running accumulated functions for too long so UI may become unresponsive, we need to
  132. // yield so the user input can be processed. Otherwise user may not be able to even close the window.
  133. // This code has effect only in case the scheduleDispatchFunctionsOnMainThread() is implemented in a way that
  134. // allows input events to be processed before we are back here.
  135. if (currentTime() - startTime > maxRunLoopSuspensionTime) {
  136. scheduleDispatchFunctionsOnMainThread();
  137. break;
  138. }
  139. }
  140. }
  141. void callOnMainThread(MainThreadFunction* function, void* context)
  142. {
  143. ASSERT(function);
  144. bool needToSchedule = false;
  145. {
  146. MutexLocker locker(mainThreadFunctionQueueMutex());
  147. needToSchedule = functionQueue().size() == 0;
  148. functionQueue().append(FunctionWithContext(function, context));
  149. }
  150. if (needToSchedule)
  151. scheduleDispatchFunctionsOnMainThread();
  152. }
  153. void callOnMainThreadAndWait(MainThreadFunction* function, void* context)
  154. {
  155. ASSERT(function);
  156. if (isMainThread()) {
  157. function(context);
  158. return;
  159. }
  160. #if USE(MANX_COND_INIT)
  161. Mutex& functionQueueMutex = mainThreadFunctionQueueMutex();
  162. ThreadCondition syncFlag(functionQueueMutex);
  163. #else
  164. ThreadCondition syncFlag;
  165. Mutex& functionQueueMutex = mainThreadFunctionQueueMutex();
  166. #endif
  167. MutexLocker locker(functionQueueMutex);
  168. functionQueue().append(FunctionWithContext(function, context, &syncFlag));
  169. if (functionQueue().size() == 1)
  170. scheduleDispatchFunctionsOnMainThread();
  171. syncFlag.wait(functionQueueMutex);
  172. }
  173. void cancelCallOnMainThread(MainThreadFunction* function, void* context)
  174. {
  175. ASSERT(function);
  176. MutexLocker locker(mainThreadFunctionQueueMutex());
  177. FunctionWithContextFinder pred(FunctionWithContext(function, context));
  178. while (true) {
  179. // We must redefine 'i' each pass, because the itererator's operator=
  180. // requires 'this' to be valid, and remove() invalidates all iterators
  181. FunctionQueue::iterator i(functionQueue().findIf(pred));
  182. if (i == functionQueue().end())
  183. break;
  184. functionQueue().remove(i);
  185. }
  186. }
  187. static void callFunctionObject(void* context)
  188. {
  189. Function<void ()>* function = static_cast<Function<void ()>*>(context);
  190. (*function)();
  191. delete function;
  192. }
  193. void callOnMainThread(const Function<void ()>& function)
  194. {
  195. callOnMainThread(callFunctionObject, new Function<void ()>(function));
  196. }
  197. void setMainThreadCallbacksPaused(bool paused)
  198. {
  199. ASSERT(isMainThread());
  200. if (callbacksPaused == paused)
  201. return;
  202. callbacksPaused = paused;
  203. if (!callbacksPaused)
  204. scheduleDispatchFunctionsOnMainThread();
  205. }
  206. #if !PLATFORM(MAC)
  207. bool isMainThread()
  208. {
  209. return currentThread() == mainThreadIdentifier;
  210. }
  211. #endif
  212. #if ENABLE(PARALLEL_GC)
  213. static ThreadSpecific<bool>* isGCThread;
  214. #endif
  215. void initializeGCThreads()
  216. {
  217. #if ENABLE(PARALLEL_GC)
  218. isGCThread = new ThreadSpecific<bool>();
  219. #endif
  220. }
  221. #if ENABLE(PARALLEL_GC)
  222. void registerGCThread()
  223. {
  224. if (!isGCThread) {
  225. // This happens if we're running in a process that doesn't care about
  226. // MainThread.
  227. return;
  228. }
  229. **isGCThread = true;
  230. }
  231. bool isMainThreadOrGCThread()
  232. {
  233. if (isGCThread->isSet() && **isGCThread)
  234. return true;
  235. return isMainThread();
  236. }
  237. #elif PLATFORM(MAC)
  238. // This is necessary because JavaScriptCore.exp doesn't support preprocessor macros.
  239. bool isMainThreadOrGCThread()
  240. {
  241. return isMainThread();
  242. }
  243. #endif
  244. } // namespace WTF