Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(144)

Side by Side Diff: Source/WTF/wtf/ThreadingWin.cpp

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

Powered by Google App Engine
This is Rietveld 408576698