]>
Commit | Line | Data |
---|---|---|
9dae56ea A |
1 | /* |
2 | * Copyright (C) 2007, 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 | * | |
9 | * 1. Redistributions of source code must retain the above copyright | |
10 | * notice, this list of conditions and the following disclaimer. | |
11 | * 2. Redistributions in binary form must reproduce the above copyright | |
12 | * notice, this list of conditions and the following disclaimer in the | |
13 | * documentation and/or other materials provided with the distribution. | |
14 | * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of | |
15 | * its contributors may be used to endorse or promote products derived | |
16 | * from this software without specific prior written permission. | |
17 | * | |
18 | * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY | |
19 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
20 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
21 | * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY | |
22 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
23 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
24 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
25 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
26 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF | |
27 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
28 | */ | |
29 | ||
30 | /* | |
31 | * There are numerous academic and practical works on how to implement pthread_cond_wait/pthread_cond_signal/pthread_cond_broadcast | |
32 | * functions on Win32. Here is one example: http://www.cs.wustl.edu/~schmidt/win32-cv-1.html which is widely credited as a 'starting point' | |
33 | * of modern attempts. There are several more or less proven implementations, one in Boost C++ library (http://www.boost.org) and another | |
34 | * in pthreads-win32 (http://sourceware.org/pthreads-win32/). | |
35 | * | |
36 | * The number of articles and discussions is the evidence of significant difficulties in implementing these primitives correctly. | |
37 | * The brief search of revisions, ChangeLog entries, discussions in comp.programming.threads and other places clearly documents | |
38 | * numerous pitfalls and performance problems the authors had to overcome to arrive to the suitable implementations. | |
39 | * Optimally, WebKit would use one of those supported/tested libraries directly. To roll out our own implementation is impractical, | |
40 | * if even for the lack of sufficient testing. However, a faithful reproduction of the code from one of the popular supported | |
41 | * libraries seems to be a good compromise. | |
42 | * | |
43 | * The early Boost implementation (http://www.boxbackup.org/trac/browser/box/nick/win/lib/win32/boost_1_32_0/libs/thread/src/condition.cpp?rev=30) | |
44 | * is identical to pthreads-win32 (http://sourceware.org/cgi-bin/cvsweb.cgi/pthreads/pthread_cond_wait.c?rev=1.10&content-type=text/x-cvsweb-markup&cvsroot=pthreads-win32). | |
45 | * Current Boost uses yet another (although seemingly equivalent) algorithm which came from their 'thread rewrite' effort. | |
46 | * | |
47 | * This file includes timedWait/signal/broadcast implementations translated to WebKit coding style from the latest algorithm by | |
48 | * Alexander Terekhov and Louis Thomas, as captured here: http://sourceware.org/cgi-bin/cvsweb.cgi/pthreads/pthread_cond_wait.c?rev=1.10&content-type=text/x-cvsweb-markup&cvsroot=pthreads-win32 | |
49 | * It replaces the implementation of their previous algorithm, also documented in the same source above. | |
50 | * The naming and comments are left very close to original to enable easy cross-check. | |
51 | * | |
52 | * The corresponding Pthreads-win32 License is included below, and CONTRIBUTORS file which it refers to is added to | |
53 | * source directory (as CONTRIBUTORS.pthreads-win32). | |
54 | */ | |
55 | ||
56 | /* | |
57 | * Pthreads-win32 - POSIX Threads Library for Win32 | |
58 | * Copyright(C) 1998 John E. Bossom | |
59 | * Copyright(C) 1999,2005 Pthreads-win32 contributors | |
60 | * | |
61 | * Contact Email: rpj@callisto.canberra.edu.au | |
62 | * | |
63 | * The current list of contributors is contained | |
64 | * in the file CONTRIBUTORS included with the source | |
65 | * code distribution. The list can also be seen at the | |
66 | * following World Wide Web location: | |
67 | * http://sources.redhat.com/pthreads-win32/contributors.html | |
68 | * | |
69 | * This library is free software; you can redistribute it and/or | |
70 | * modify it under the terms of the GNU Lesser General Public | |
71 | * License as published by the Free Software Foundation; either | |
72 | * version 2 of the License, or (at your option) any later version. | |
73 | * | |
74 | * This library is distributed in the hope that it will be useful, | |
75 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
76 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
77 | * Lesser General Public License for more details. | |
78 | * | |
79 | * You should have received a copy of the GNU Lesser General Public | |
80 | * License along with this library in the file COPYING.LIB; | |
81 | * if not, write to the Free Software Foundation, Inc., | |
82 | * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA | |
83 | */ | |
84 | ||
85 | #include "config.h" | |
86 | #include "Threading.h" | |
87 | ||
88 | #include "MainThread.h" | |
89 | #if !USE(PTHREADS) && PLATFORM(WIN_OS) | |
90 | #include "ThreadSpecific.h" | |
91 | #endif | |
92 | #include <process.h> | |
93 | #include <windows.h> | |
94 | #include <wtf/CurrentTime.h> | |
95 | #include <wtf/HashMap.h> | |
96 | #include <wtf/MathExtras.h> | |
97 | #include <wtf/RandomNumberSeed.h> | |
98 | ||
99 | namespace WTF { | |
100 | ||
101 | // MS_VC_EXCEPTION, THREADNAME_INFO, and setThreadName all come from <http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx>. | |
102 | static const DWORD MS_VC_EXCEPTION = 0x406D1388; | |
103 | ||
104 | #pragma pack(push, 8) | |
105 | typedef struct tagTHREADNAME_INFO { | |
106 | DWORD dwType; // must be 0x1000 | |
107 | LPCSTR szName; // pointer to name (in user addr space) | |
108 | DWORD dwThreadID; // thread ID (-1=caller thread) | |
109 | DWORD dwFlags; // reserved for future use, must be zero | |
110 | } THREADNAME_INFO; | |
111 | #pragma pack(pop) | |
112 | ||
113 | static void setThreadName(DWORD dwThreadID, LPCSTR szThreadName) | |
114 | { | |
115 | // Visual Studio has a 31-character limit on thread names. Longer names will | |
116 | // be truncated silently, but we'd like callers to know about the limit. | |
117 | ASSERT_ARG(szThreadName, strlen(szThreadName) <= 31); | |
118 | ||
119 | THREADNAME_INFO info; | |
120 | info.dwType = 0x1000; | |
121 | info.szName = szThreadName; | |
122 | info.dwThreadID = dwThreadID; | |
123 | info.dwFlags = 0; | |
124 | ||
125 | __try { | |
126 | RaiseException(MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), reinterpret_cast<ULONG_PTR*>(&info)); | |
127 | } __except (EXCEPTION_CONTINUE_EXECUTION) { | |
128 | } | |
129 | } | |
130 | ||
131 | static Mutex* atomicallyInitializedStaticMutex; | |
132 | ||
133 | void lockAtomicallyInitializedStaticMutex() | |
134 | { | |
135 | ASSERT(atomicallyInitializedStaticMutex); | |
136 | atomicallyInitializedStaticMutex->lock(); | |
137 | } | |
138 | ||
139 | void unlockAtomicallyInitializedStaticMutex() | |
140 | { | |
141 | atomicallyInitializedStaticMutex->unlock(); | |
142 | } | |
143 | ||
144 | static ThreadIdentifier mainThreadIdentifier; | |
145 | ||
146 | static Mutex& threadMapMutex() | |
147 | { | |
148 | static Mutex mutex; | |
149 | return mutex; | |
150 | } | |
151 | ||
152 | void initializeThreading() | |
153 | { | |
154 | if (!atomicallyInitializedStaticMutex) { | |
155 | atomicallyInitializedStaticMutex = new Mutex; | |
156 | threadMapMutex(); | |
157 | initializeRandomNumberGenerator(); | |
158 | initializeMainThread(); | |
159 | mainThreadIdentifier = currentThread(); | |
160 | setThreadName(mainThreadIdentifier, "Main Thread"); | |
161 | } | |
162 | } | |
163 | ||
164 | static HashMap<DWORD, HANDLE>& threadMap() | |
165 | { | |
166 | static HashMap<DWORD, HANDLE> map; | |
167 | return map; | |
168 | } | |
169 | ||
170 | static void storeThreadHandleByIdentifier(DWORD threadID, HANDLE threadHandle) | |
171 | { | |
172 | MutexLocker locker(threadMapMutex()); | |
173 | ASSERT(!threadMap().contains(threadID)); | |
174 | threadMap().add(threadID, threadHandle); | |
175 | } | |
176 | ||
177 | static HANDLE threadHandleForIdentifier(ThreadIdentifier id) | |
178 | { | |
179 | MutexLocker locker(threadMapMutex()); | |
180 | return threadMap().get(id); | |
181 | } | |
182 | ||
183 | static void clearThreadHandleForIdentifier(ThreadIdentifier id) | |
184 | { | |
185 | MutexLocker locker(threadMapMutex()); | |
186 | ASSERT(threadMap().contains(id)); | |
187 | threadMap().remove(id); | |
188 | } | |
189 | ||
190 | struct ThreadFunctionInvocation { | |
191 | ThreadFunctionInvocation(ThreadFunction function, void* data) : function(function), data(data) {} | |
192 | ||
193 | ThreadFunction function; | |
194 | void* data; | |
195 | }; | |
196 | ||
197 | static unsigned __stdcall wtfThreadEntryPoint(void* param) | |
198 | { | |
199 | ThreadFunctionInvocation invocation = *static_cast<ThreadFunctionInvocation*>(param); | |
200 | delete static_cast<ThreadFunctionInvocation*>(param); | |
201 | ||
202 | void* result = invocation.function(invocation.data); | |
203 | ||
204 | #if !USE(PTHREADS) && PLATFORM(WIN_OS) | |
205 | // Do the TLS cleanup. | |
206 | ThreadSpecificThreadExit(); | |
207 | #endif | |
208 | ||
209 | return reinterpret_cast<unsigned>(result); | |
210 | } | |
211 | ||
212 | ThreadIdentifier createThreadInternal(ThreadFunction entryPoint, void* data, const char* threadName) | |
213 | { | |
214 | unsigned threadIdentifier = 0; | |
215 | ThreadIdentifier threadID = 0; | |
216 | ThreadFunctionInvocation* invocation = new ThreadFunctionInvocation(entryPoint, data); | |
217 | HANDLE threadHandle = reinterpret_cast<HANDLE>(_beginthreadex(0, 0, wtfThreadEntryPoint, invocation, 0, &threadIdentifier)); | |
218 | if (!threadHandle) { | |
219 | LOG_ERROR("Failed to create thread at entry point %p with data %p: %ld", entryPoint, data, errno); | |
220 | return 0; | |
221 | } | |
222 | ||
223 | if (threadName) | |
224 | setThreadName(threadIdentifier, threadName); | |
225 | ||
226 | threadID = static_cast<ThreadIdentifier>(threadIdentifier); | |
227 | storeThreadHandleByIdentifier(threadIdentifier, threadHandle); | |
228 | ||
229 | return threadID; | |
230 | } | |
231 | ||
232 | int waitForThreadCompletion(ThreadIdentifier threadID, void** result) | |
233 | { | |
234 | ASSERT(threadID); | |
235 | ||
236 | HANDLE threadHandle = threadHandleForIdentifier(threadID); | |
237 | if (!threadHandle) | |
238 | LOG_ERROR("ThreadIdentifier %u did not correspond to an active thread when trying to quit", threadID); | |
239 | ||
240 | DWORD joinResult = WaitForSingleObject(threadHandle, INFINITE); | |
241 | if (joinResult == WAIT_FAILED) | |
242 | LOG_ERROR("ThreadIdentifier %u was found to be deadlocked trying to quit", threadID); | |
243 | ||
244 | CloseHandle(threadHandle); | |
245 | clearThreadHandleForIdentifier(threadID); | |
246 | ||
247 | return joinResult; | |
248 | } | |
249 | ||
250 | void detachThread(ThreadIdentifier threadID) | |
251 | { | |
252 | ASSERT(threadID); | |
253 | ||
254 | HANDLE threadHandle = threadHandleForIdentifier(threadID); | |
255 | if (threadHandle) | |
256 | CloseHandle(threadHandle); | |
257 | clearThreadHandleForIdentifier(threadID); | |
258 | } | |
259 | ||
260 | ThreadIdentifier currentThread() | |
261 | { | |
262 | return static_cast<ThreadIdentifier>(GetCurrentThreadId()); | |
263 | } | |
264 | ||
265 | bool isMainThread() | |
266 | { | |
267 | return currentThread() == mainThreadIdentifier; | |
268 | } | |
269 | ||
270 | Mutex::Mutex() | |
271 | { | |
272 | m_mutex.m_recursionCount = 0; | |
273 | InitializeCriticalSection(&m_mutex.m_internalMutex); | |
274 | } | |
275 | ||
276 | Mutex::~Mutex() | |
277 | { | |
278 | DeleteCriticalSection(&m_mutex.m_internalMutex); | |
279 | } | |
280 | ||
281 | void Mutex::lock() | |
282 | { | |
283 | EnterCriticalSection(&m_mutex.m_internalMutex); | |
284 | ++m_mutex.m_recursionCount; | |
285 | } | |
286 | ||
287 | bool Mutex::tryLock() | |
288 | { | |
289 | // This method is modeled after the behavior of pthread_mutex_trylock, | |
290 | // which will return an error if the lock is already owned by the | |
291 | // current thread. Since the primitive Win32 'TryEnterCriticalSection' | |
292 | // treats this as a successful case, it changes the behavior of several | |
293 | // tests in WebKit that check to see if the current thread already | |
294 | // owned this mutex (see e.g., IconDatabase::getOrCreateIconRecord) | |
295 | DWORD result = TryEnterCriticalSection(&m_mutex.m_internalMutex); | |
296 | ||
297 | if (result != 0) { // We got the lock | |
298 | // If this thread already had the lock, we must unlock and | |
299 | // return false so that we mimic the behavior of POSIX's | |
300 | // pthread_mutex_trylock: | |
301 | if (m_mutex.m_recursionCount > 0) { | |
302 | LeaveCriticalSection(&m_mutex.m_internalMutex); | |
303 | return false; | |
304 | } | |
305 | ||
306 | ++m_mutex.m_recursionCount; | |
307 | return true; | |
308 | } | |
309 | ||
310 | return false; | |
311 | } | |
312 | ||
313 | void Mutex::unlock() | |
314 | { | |
315 | --m_mutex.m_recursionCount; | |
316 | LeaveCriticalSection(&m_mutex.m_internalMutex); | |
317 | } | |
318 | ||
319 | bool PlatformCondition::timedWait(PlatformMutex& mutex, DWORD durationMilliseconds) | |
320 | { | |
321 | // Enter the wait state. | |
322 | DWORD res = WaitForSingleObject(m_blockLock, INFINITE); | |
323 | ASSERT(res == WAIT_OBJECT_0); | |
324 | ++m_waitersBlocked; | |
325 | res = ReleaseSemaphore(m_blockLock, 1, 0); | |
326 | ASSERT(res); | |
327 | ||
328 | LeaveCriticalSection(&mutex.m_internalMutex); | |
329 | ||
330 | // Main wait - use timeout. | |
331 | bool timedOut = (WaitForSingleObject(m_blockQueue, durationMilliseconds) == WAIT_TIMEOUT); | |
332 | ||
333 | res = WaitForSingleObject(m_unblockLock, INFINITE); | |
334 | ASSERT(res == WAIT_OBJECT_0); | |
335 | ||
336 | int signalsLeft = m_waitersToUnblock; | |
337 | ||
338 | if (m_waitersToUnblock) | |
339 | --m_waitersToUnblock; | |
340 | else if (++m_waitersGone == (INT_MAX / 2)) { // timeout/canceled or spurious semaphore | |
341 | // timeout or spurious wakeup occured, normalize the m_waitersGone count | |
342 | // this may occur if many calls to wait with a timeout are made and | |
343 | // no call to notify_* is made | |
344 | res = WaitForSingleObject(m_blockLock, INFINITE); | |
345 | ASSERT(res == WAIT_OBJECT_0); | |
346 | m_waitersBlocked -= m_waitersGone; | |
347 | res = ReleaseSemaphore(m_blockLock, 1, 0); | |
348 | ASSERT(res); | |
349 | m_waitersGone = 0; | |
350 | } | |
351 | ||
352 | res = ReleaseMutex(m_unblockLock); | |
353 | ASSERT(res); | |
354 | ||
355 | if (signalsLeft == 1) { | |
356 | res = ReleaseSemaphore(m_blockLock, 1, 0); // Open the gate. | |
357 | ASSERT(res); | |
358 | } | |
359 | ||
360 | EnterCriticalSection (&mutex.m_internalMutex); | |
361 | ||
362 | return !timedOut; | |
363 | } | |
364 | ||
365 | void PlatformCondition::signal(bool unblockAll) | |
366 | { | |
367 | unsigned signalsToIssue = 0; | |
368 | ||
369 | DWORD res = WaitForSingleObject(m_unblockLock, INFINITE); | |
370 | ASSERT(res == WAIT_OBJECT_0); | |
371 | ||
372 | if (m_waitersToUnblock) { // the gate is already closed | |
373 | if (!m_waitersBlocked) { // no-op | |
374 | res = ReleaseMutex(m_unblockLock); | |
375 | ASSERT(res); | |
376 | return; | |
377 | } | |
378 | ||
379 | if (unblockAll) { | |
380 | signalsToIssue = m_waitersBlocked; | |
381 | m_waitersToUnblock += m_waitersBlocked; | |
382 | m_waitersBlocked = 0; | |
383 | } else { | |
384 | signalsToIssue = 1; | |
385 | ++m_waitersToUnblock; | |
386 | --m_waitersBlocked; | |
387 | } | |
388 | } else if (m_waitersBlocked > m_waitersGone) { | |
389 | res = WaitForSingleObject(m_blockLock, INFINITE); // Close the gate. | |
390 | ASSERT(res == WAIT_OBJECT_0); | |
391 | if (m_waitersGone != 0) { | |
392 | m_waitersBlocked -= m_waitersGone; | |
393 | m_waitersGone = 0; | |
394 | } | |
395 | if (unblockAll) { | |
396 | signalsToIssue = m_waitersBlocked; | |
397 | m_waitersToUnblock = m_waitersBlocked; | |
398 | m_waitersBlocked = 0; | |
399 | } else { | |
400 | signalsToIssue = 1; | |
401 | m_waitersToUnblock = 1; | |
402 | --m_waitersBlocked; | |
403 | } | |
404 | } else { // No-op. | |
405 | res = ReleaseMutex(m_unblockLock); | |
406 | ASSERT(res); | |
407 | return; | |
408 | } | |
409 | ||
410 | res = ReleaseMutex(m_unblockLock); | |
411 | ASSERT(res); | |
412 | ||
413 | if (signalsToIssue) { | |
414 | res = ReleaseSemaphore(m_blockQueue, signalsToIssue, 0); | |
415 | ASSERT(res); | |
416 | } | |
417 | } | |
418 | ||
419 | static const long MaxSemaphoreCount = static_cast<long>(~0UL >> 1); | |
420 | ||
421 | ThreadCondition::ThreadCondition() | |
422 | { | |
423 | m_condition.m_waitersGone = 0; | |
424 | m_condition.m_waitersBlocked = 0; | |
425 | m_condition.m_waitersToUnblock = 0; | |
426 | m_condition.m_blockLock = CreateSemaphore(0, 1, 1, 0); | |
427 | m_condition.m_blockQueue = CreateSemaphore(0, 0, MaxSemaphoreCount, 0); | |
428 | m_condition.m_unblockLock = CreateMutex(0, 0, 0); | |
429 | ||
430 | if (!m_condition.m_blockLock || !m_condition.m_blockQueue || !m_condition.m_unblockLock) { | |
431 | if (m_condition.m_blockLock) | |
432 | CloseHandle(m_condition.m_blockLock); | |
433 | if (m_condition.m_blockQueue) | |
434 | CloseHandle(m_condition.m_blockQueue); | |
435 | if (m_condition.m_unblockLock) | |
436 | CloseHandle(m_condition.m_unblockLock); | |
437 | } | |
438 | } | |
439 | ||
440 | ThreadCondition::~ThreadCondition() | |
441 | { | |
442 | CloseHandle(m_condition.m_blockLock); | |
443 | CloseHandle(m_condition.m_blockQueue); | |
444 | CloseHandle(m_condition.m_unblockLock); | |
445 | } | |
446 | ||
447 | void ThreadCondition::wait(Mutex& mutex) | |
448 | { | |
449 | m_condition.timedWait(mutex.impl(), INFINITE); | |
450 | } | |
451 | ||
452 | bool ThreadCondition::timedWait(Mutex& mutex, double absoluteTime) | |
453 | { | |
454 | double currentTime = WTF::currentTime(); | |
455 | ||
456 | // Time is in the past - return immediately. | |
457 | if (absoluteTime < currentTime) | |
458 | return false; | |
459 | ||
460 | double intervalMilliseconds = (absoluteTime - currentTime) * 1000.0; | |
461 | if (intervalMilliseconds >= INT_MAX) | |
462 | intervalMilliseconds = INT_MAX; | |
463 | ||
464 | return m_condition.timedWait(mutex.impl(), static_cast<unsigned long>(intervalMilliseconds)); | |
465 | } | |
466 | ||
467 | void ThreadCondition::signal() | |
468 | { | |
469 | m_condition.signal(false); // Unblock only 1 thread. | |
470 | } | |
471 | ||
472 | void ThreadCondition::broadcast() | |
473 | { | |
474 | m_condition.signal(true); // Unblock all threads. | |
475 | } | |
476 | ||
477 | } // namespace WTF |