Home | History | Annotate | Download | only in wtf
      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_cond_wait/pthread_cond_signal/pthread_cond_broadcast
     33  * 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'
     34  * of modern attempts. There are several more or less proven implementations, one 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 difficulties in implementing these primitives correctly.
     38  * The brief search of revisions, ChangeLog entries, discussions in comp.programming.threads and other places clearly documents
     39  * numerous pitfalls and performance problems the authors had to overcome to arrive 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/nick/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/pthreads/pthread_cond_wait.c?rev=1.10&content-type=text/x-cvsweb-markup&cvsroot=pthreads-win32).
     46  * Current Boost uses yet another (although seemingly equivalent) algorithm which came from their 'thread rewrite' effort.
     47  *
     48  * This file includes timedWait/signal/broadcast implementations translated to WebKit 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-cvsweb-markup&cvsroot=pthreads-win32
     50  * It replaces the implementation of their previous algorithm, also documented in 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 (at) 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(WIN)
     90 
     91 #include "wtf/CurrentTime.h"
     92 #include "wtf/DateMath.h"
     93 #include "wtf/HashMap.h"
     94 #include "wtf/MainThread.h"
     95 #include "wtf/MathExtras.h"
     96 #include "wtf/OwnPtr.h"
     97 #include "wtf/PassOwnPtr.h"
     98 #include "wtf/ThreadFunctionInvocation.h"
     99 #include "wtf/ThreadSpecific.h"
    100 #include "wtf/ThreadingPrimitives.h"
    101 #include "wtf/WTFThreadData.h"
    102 #include "wtf/dtoa.h"
    103 #include "wtf/dtoa/cached-powers.h"
    104 #include <errno.h>
    105 #include <process.h>
    106 #include <windows.h>
    107 
    108 namespace WTF {
    109 
    110 // MS_VC_EXCEPTION, THREADNAME_INFO, and setThreadNameInternal all come from <http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx>.
    111 static const DWORD MS_VC_EXCEPTION = 0x406D1388;
    112 
    113 #pragma pack(push, 8)
    114 typedef struct tagTHREADNAME_INFO {
    115     DWORD dwType; // must be 0x1000
    116     LPCSTR szName; // pointer to name (in user addr space)
    117     DWORD dwThreadID; // thread ID (-1=caller thread)
    118     DWORD dwFlags; // reserved for future use, must be zero
    119 } THREADNAME_INFO;
    120 #pragma pack(pop)
    121 
    122 void initializeCurrentThreadInternal(const char* szThreadName)
    123 {
    124     THREADNAME_INFO info;
    125     info.dwType = 0x1000;
    126     info.szName = szThreadName;
    127     info.dwThreadID = GetCurrentThreadId();
    128     info.dwFlags = 0;
    129 
    130     __try {
    131         RaiseException(MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), reinterpret_cast<ULONG_PTR*>(&info));
    132     } __except (EXCEPTION_CONTINUE_EXECUTION) {
    133     }
    134 }
    135 
    136 static Mutex* atomicallyInitializedStaticMutex;
    137 
    138 void lockAtomicallyInitializedStaticMutex()
    139 {
    140     ASSERT(atomicallyInitializedStaticMutex);
    141     atomicallyInitializedStaticMutex->lock();
    142 }
    143 
    144 void unlockAtomicallyInitializedStaticMutex()
    145 {
    146     atomicallyInitializedStaticMutex->unlock();
    147 }
    148 
    149 static Mutex& threadMapMutex()
    150 {
    151     static Mutex mutex;
    152     return mutex;
    153 }
    154 
    155 void initializeThreading()
    156 {
    157     // This should only be called once.
    158     ASSERT(!atomicallyInitializedStaticMutex);
    159 
    160     // StringImpl::empty() does not construct its static string in a threadsafe fashion,
    161     // so ensure it has been initialized from here.
    162     StringImpl::empty();
    163     atomicallyInitializedStaticMutex = new Mutex;
    164     threadMapMutex();
    165     wtfThreadData();
    166     s_dtoaP5Mutex = new Mutex;
    167     initializeDates();
    168 }
    169 
    170 static HashMap<DWORD, HANDLE>& threadMap()
    171 {
    172     static HashMap<DWORD, HANDLE>* gMap;
    173     if (!gMap)
    174         gMap = new HashMap<DWORD, HANDLE>();
    175     return *gMap;
    176 }
    177 
    178 static void storeThreadHandleByIdentifier(DWORD threadID, HANDLE threadHandle)
    179 {
    180     MutexLocker locker(threadMapMutex());
    181     ASSERT(!threadMap().contains(threadID));
    182     threadMap().add(threadID, threadHandle);
    183 }
    184 
    185 static HANDLE threadHandleForIdentifier(ThreadIdentifier id)
    186 {
    187     MutexLocker locker(threadMapMutex());
    188     return threadMap().get(id);
    189 }
    190 
    191 static void clearThreadHandleForIdentifier(ThreadIdentifier id)
    192 {
    193     MutexLocker locker(threadMapMutex());
    194     ASSERT(threadMap().contains(id));
    195     threadMap().remove(id);
    196 }
    197 
    198 static unsigned __stdcall wtfThreadEntryPoint(void* param)
    199 {
    200     OwnPtr<ThreadFunctionInvocation> invocation = adoptPtr(static_cast<ThreadFunctionInvocation*>(param));
    201     invocation->function(invocation->data);
    202 
    203     // Do the TLS cleanup.
    204     ThreadSpecificThreadExit();
    205 
    206     return 0;
    207 }
    208 
    209 ThreadIdentifier createThreadInternal(ThreadFunction entryPoint, void* data, const char* threadName)
    210 {
    211     unsigned threadIdentifier = 0;
    212     ThreadIdentifier threadID = 0;
    213     OwnPtr<ThreadFunctionInvocation> invocation = adoptPtr(new ThreadFunctionInvocation(entryPoint, data));
    214     HANDLE threadHandle = reinterpret_cast<HANDLE>(_beginthreadex(0, 0, wtfThreadEntryPoint, invocation.get(), 0, &threadIdentifier));
    215     if (!threadHandle) {
    216         WTF_LOG_ERROR("Failed to create thread at entry point %p with data %p: %ld", entryPoint, data, errno);
    217         return 0;
    218     }
    219 
    220     // The thread will take ownership of invocation.
    221     ThreadFunctionInvocation* ALLOW_UNUSED leakedInvocation = invocation.leakPtr();
    222 
    223     threadID = static_cast<ThreadIdentifier>(threadIdentifier);
    224     storeThreadHandleByIdentifier(threadIdentifier, threadHandle);
    225 
    226     return threadID;
    227 }
    228 
    229 int waitForThreadCompletion(ThreadIdentifier threadID)
    230 {
    231     ASSERT(threadID);
    232 
    233     HANDLE threadHandle = threadHandleForIdentifier(threadID);
    234     if (!threadHandle)
    235         WTF_LOG_ERROR("ThreadIdentifier %u did not correspond to an active thread when trying to quit", threadID);
    236 
    237     DWORD joinResult = WaitForSingleObject(threadHandle, INFINITE);
    238     if (joinResult == WAIT_FAILED)
    239         WTF_LOG_ERROR("ThreadIdentifier %u was found to be deadlocked trying to quit", threadID);
    240 
    241     CloseHandle(threadHandle);
    242     clearThreadHandleForIdentifier(threadID);
    243 
    244     return joinResult;
    245 }
    246 
    247 void detachThread(ThreadIdentifier threadID)
    248 {
    249     ASSERT(threadID);
    250 
    251     HANDLE threadHandle = threadHandleForIdentifier(threadID);
    252     if (threadHandle)
    253         CloseHandle(threadHandle);
    254     clearThreadHandleForIdentifier(threadID);
    255 }
    256 
    257 void yield()
    258 {
    259     ::Sleep(1);
    260 }
    261 
    262 ThreadIdentifier currentThread()
    263 {
    264     return static_cast<ThreadIdentifier>(GetCurrentThreadId());
    265 }
    266 
    267 Mutex::Mutex()
    268 {
    269     m_mutex.m_recursionCount = 0;
    270     InitializeCriticalSection(&m_mutex.m_internalMutex);
    271 }
    272 
    273 Mutex::~Mutex()
    274 {
    275     DeleteCriticalSection(&m_mutex.m_internalMutex);
    276 }
    277 
    278 void Mutex::lock()
    279 {
    280     EnterCriticalSection(&m_mutex.m_internalMutex);
    281     ++m_mutex.m_recursionCount;
    282 }
    283 
    284 bool Mutex::tryLock()
    285 {
    286     // This method is modeled after the behavior of pthread_mutex_trylock,
    287     // which will return an error if the lock is already owned by the
    288     // current thread.  Since the primitive Win32 'TryEnterCriticalSection'
    289     // treats this as a successful case, it changes the behavior of several
    290     // tests in WebKit that check to see if the current thread already
    291     // owned this mutex (see e.g., IconDatabase::getOrCreateIconRecord)
    292     DWORD result = TryEnterCriticalSection(&m_mutex.m_internalMutex);
    293 
    294     if (result != 0) {       // We got the lock
    295         // If this thread already had the lock, we must unlock and
    296         // return false so that we mimic the behavior of POSIX's
    297         // pthread_mutex_trylock:
    298         if (m_mutex.m_recursionCount > 0) {
    299             LeaveCriticalSection(&m_mutex.m_internalMutex);
    300             return false;
    301         }
    302 
    303         ++m_mutex.m_recursionCount;
    304         return true;
    305     }
    306 
    307     return false;
    308 }
    309 
    310 void Mutex::unlock()
    311 {
    312     ASSERT(m_mutex.m_recursionCount);
    313     --m_mutex.m_recursionCount;
    314     LeaveCriticalSection(&m_mutex.m_internalMutex);
    315 }
    316 
    317 bool PlatformCondition::timedWait(PlatformMutex& mutex, DWORD durationMilliseconds)
    318 {
    319     // Enter the wait state.
    320     DWORD res = WaitForSingleObject(m_blockLock, INFINITE);
    321     ASSERT_UNUSED(res, res == WAIT_OBJECT_0);
    322     ++m_waitersBlocked;
    323     res = ReleaseSemaphore(m_blockLock, 1, 0);
    324     ASSERT_UNUSED(res, res);
    325 
    326     --mutex.m_recursionCount;
    327     LeaveCriticalSection(&mutex.m_internalMutex);
    328 
    329     // Main wait - use timeout.
    330     bool timedOut = (WaitForSingleObject(m_blockQueue, durationMilliseconds) == WAIT_TIMEOUT);
    331 
    332     res = WaitForSingleObject(m_unblockLock, INFINITE);
    333     ASSERT_UNUSED(res, res == WAIT_OBJECT_0);
    334 
    335     int signalsLeft = m_waitersToUnblock;
    336 
    337     if (m_waitersToUnblock)
    338         --m_waitersToUnblock;
    339     else if (++m_waitersGone == (INT_MAX / 2)) { // timeout/canceled or spurious semaphore
    340         // timeout or spurious wakeup occured, normalize the m_waitersGone count
    341         // this may occur if many calls to wait with a timeout are made and
    342         // no call to notify_* is made
    343         res = WaitForSingleObject(m_blockLock, INFINITE);
    344         ASSERT_UNUSED(res, res == WAIT_OBJECT_0);
    345         m_waitersBlocked -= m_waitersGone;
    346         res = ReleaseSemaphore(m_blockLock, 1, 0);
    347         ASSERT_UNUSED(res, res);
    348         m_waitersGone = 0;
    349     }
    350 
    351     res = ReleaseMutex(m_unblockLock);
    352     ASSERT_UNUSED(res, res);
    353 
    354     if (signalsLeft == 1) {
    355         res = ReleaseSemaphore(m_blockLock, 1, 0); // Open the gate.
    356         ASSERT_UNUSED(res, res);
    357     }
    358 
    359     EnterCriticalSection (&mutex.m_internalMutex);
    360     ++mutex.m_recursionCount;
    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_UNUSED(res, 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_UNUSED(res, 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_UNUSED(res, 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_UNUSED(res, res);
    407         return;
    408     }
    409 
    410     res = ReleaseMutex(m_unblockLock);
    411     ASSERT_UNUSED(res, res);
    412 
    413     if (signalsToIssue) {
    414         res = ReleaseSemaphore(m_blockQueue, signalsToIssue, 0);
    415         ASSERT_UNUSED(res, 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     DWORD interval = absoluteTimeToWaitTimeoutInterval(absoluteTime);
    455 
    456     if (!interval) {
    457         // Consider the wait to have timed out, even if our condition has already been signaled, to
    458         // match the pthreads implementation.
    459         return false;
    460     }
    461 
    462     return m_condition.timedWait(mutex.impl(), interval);
    463 }
    464 
    465 void ThreadCondition::signal()
    466 {
    467     m_condition.signal(false); // Unblock only 1 thread.
    468 }
    469 
    470 void ThreadCondition::broadcast()
    471 {
    472     m_condition.signal(true); // Unblock all threads.
    473 }
    474 
    475 DWORD absoluteTimeToWaitTimeoutInterval(double absoluteTime)
    476 {
    477     double currentTime = WTF::currentTime();
    478 
    479     // Time is in the past - return immediately.
    480     if (absoluteTime < currentTime)
    481         return 0;
    482 
    483     // Time is too far in the future (and would overflow unsigned long) - wait forever.
    484     if (absoluteTime - currentTime > static_cast<double>(INT_MAX) / 1000.0)
    485         return INFINITE;
    486 
    487     return static_cast<DWORD>((absoluteTime - currentTime) * 1000.0);
    488 }
    489 
    490 } // namespace WTF
    491 
    492 #endif // OS(WIN)
    493