• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007, 2009 Apple Inc. All rights reserved.
3  * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com)
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 #include "config.h"
31 #include "Threading.h"
32 
33 #if USE(PTHREADS)
34 
35 #include "CurrentTime.h"
36 #include "HashMap.h"
37 #include "MainThread.h"
38 #include "RandomNumberSeed.h"
39 #include "StdLibExtras.h"
40 #include "UnusedParam.h"
41 #include <errno.h>
42 #include <limits.h>
43 #include <sys/time.h>
44 
45 #if PLATFORM(ANDROID)
46 #include "jni_utility.h"
47 #endif
48 
49 namespace WTF {
50 
51 typedef HashMap<ThreadIdentifier, pthread_t> ThreadMap;
52 
53 static Mutex* atomicallyInitializedStaticMutex;
54 
55 #if !PLATFORM(DARWIN) || PLATFORM(CHROMIUM)
56 static ThreadIdentifier mainThreadIdentifier; // The thread that was the first to call initializeThreading(), which must be the main thread.
57 #endif
58 
threadMapMutex()59 static Mutex& threadMapMutex()
60 {
61     DEFINE_STATIC_LOCAL(Mutex, mutex, ());
62     return mutex;
63 }
64 
initializeThreading()65 void initializeThreading()
66 {
67     if (!atomicallyInitializedStaticMutex) {
68         atomicallyInitializedStaticMutex = new Mutex;
69         threadMapMutex();
70         initializeRandomNumberGenerator();
71 #if !PLATFORM(DARWIN) || PLATFORM(CHROMIUM)
72         mainThreadIdentifier = currentThread();
73 #endif
74         initializeMainThread();
75     }
76 }
77 
lockAtomicallyInitializedStaticMutex()78 void lockAtomicallyInitializedStaticMutex()
79 {
80     ASSERT(atomicallyInitializedStaticMutex);
81     atomicallyInitializedStaticMutex->lock();
82 }
83 
unlockAtomicallyInitializedStaticMutex()84 void unlockAtomicallyInitializedStaticMutex()
85 {
86     atomicallyInitializedStaticMutex->unlock();
87 }
88 
threadMap()89 static ThreadMap& threadMap()
90 {
91     DEFINE_STATIC_LOCAL(ThreadMap, map, ());
92     return map;
93 }
94 
identifierByPthreadHandle(const pthread_t & pthreadHandle)95 static ThreadIdentifier identifierByPthreadHandle(const pthread_t& pthreadHandle)
96 {
97     MutexLocker locker(threadMapMutex());
98 
99     ThreadMap::iterator i = threadMap().begin();
100     for (; i != threadMap().end(); ++i) {
101         if (pthread_equal(i->second, pthreadHandle))
102             return i->first;
103     }
104 
105     return 0;
106 }
107 
establishIdentifierForPthreadHandle(pthread_t & pthreadHandle)108 static ThreadIdentifier establishIdentifierForPthreadHandle(pthread_t& pthreadHandle)
109 {
110     ASSERT(!identifierByPthreadHandle(pthreadHandle));
111 
112     MutexLocker locker(threadMapMutex());
113 
114     static ThreadIdentifier identifierCount = 1;
115 
116     threadMap().add(identifierCount, pthreadHandle);
117 
118     return identifierCount++;
119 }
120 
pthreadHandleForIdentifier(ThreadIdentifier id)121 static pthread_t pthreadHandleForIdentifier(ThreadIdentifier id)
122 {
123     MutexLocker locker(threadMapMutex());
124 
125     return threadMap().get(id);
126 }
127 
clearPthreadHandleForIdentifier(ThreadIdentifier id)128 static void clearPthreadHandleForIdentifier(ThreadIdentifier id)
129 {
130     MutexLocker locker(threadMapMutex());
131 
132     ASSERT(threadMap().contains(id));
133 
134     threadMap().remove(id);
135 }
136 
137 #if PLATFORM(ANDROID)
138 // On the Android platform, threads must be registered with the VM before they run.
139 struct ThreadData {
140     ThreadFunction entryPoint;
141     void* arg;
142 };
143 
runThreadWithRegistration(void * arg)144 static void* runThreadWithRegistration(void* arg)
145 {
146     ThreadData* data = static_cast<ThreadData*>(arg);
147     JavaVM* vm = JSC::Bindings::getJavaVM();
148     JNIEnv* env;
149     void* ret = 0;
150     if (vm->AttachCurrentThread(&env, 0) == JNI_OK) {
151         ret = data->entryPoint(data->arg);
152         vm->DetachCurrentThread();
153     }
154     delete data;
155     return ret;
156 }
157 
createThreadInternal(ThreadFunction entryPoint,void * data,const char *)158 ThreadIdentifier createThreadInternal(ThreadFunction entryPoint, void* data, const char*)
159 {
160     pthread_t threadHandle;
161     ThreadData* threadData = new ThreadData();
162     threadData->entryPoint = entryPoint;
163     threadData->arg = data;
164 
165     if (pthread_create(&threadHandle, 0, runThreadWithRegistration, static_cast<void*>(threadData))) {
166         LOG_ERROR("Failed to create pthread at entry point %p with data %p", entryPoint, data);
167         delete threadData;
168         return 0;
169     }
170     return establishIdentifierForPthreadHandle(threadHandle);
171 }
172 #else
createThreadInternal(ThreadFunction entryPoint,void * data,const char *)173 ThreadIdentifier createThreadInternal(ThreadFunction entryPoint, void* data, const char*)
174 {
175     pthread_t threadHandle;
176     if (pthread_create(&threadHandle, 0, entryPoint, data)) {
177         LOG_ERROR("Failed to create pthread at entry point %p with data %p", entryPoint, data);
178         return 0;
179     }
180 
181     return establishIdentifierForPthreadHandle(threadHandle);
182 }
183 #endif
184 
setThreadNameInternal(const char * threadName)185 void setThreadNameInternal(const char* threadName)
186 {
187 #if PLATFORM(DARWIN) && !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) && !PLATFORM(IPHONE)
188     pthread_setname_np(threadName);
189 #else
190     UNUSED_PARAM(threadName);
191 #endif
192 }
193 
waitForThreadCompletion(ThreadIdentifier threadID,void ** result)194 int waitForThreadCompletion(ThreadIdentifier threadID, void** result)
195 {
196     ASSERT(threadID);
197 
198     pthread_t pthreadHandle = pthreadHandleForIdentifier(threadID);
199 
200     int joinResult = pthread_join(pthreadHandle, result);
201     if (joinResult == EDEADLK)
202         LOG_ERROR("ThreadIdentifier %u was found to be deadlocked trying to quit", threadID);
203 
204     clearPthreadHandleForIdentifier(threadID);
205     return joinResult;
206 }
207 
detachThread(ThreadIdentifier threadID)208 void detachThread(ThreadIdentifier threadID)
209 {
210     ASSERT(threadID);
211 
212     pthread_t pthreadHandle = pthreadHandleForIdentifier(threadID);
213 
214     pthread_detach(pthreadHandle);
215 
216     clearPthreadHandleForIdentifier(threadID);
217 }
218 
currentThread()219 ThreadIdentifier currentThread()
220 {
221     pthread_t currentThread = pthread_self();
222     if (ThreadIdentifier id = identifierByPthreadHandle(currentThread))
223         return id;
224     return establishIdentifierForPthreadHandle(currentThread);
225 }
226 
isMainThread()227 bool isMainThread()
228 {
229 #if PLATFORM(DARWIN) && !PLATFORM(CHROMIUM)
230     return pthread_main_np();
231 #else
232     return currentThread() == mainThreadIdentifier;
233 #endif
234 }
235 
Mutex()236 Mutex::Mutex()
237 {
238     pthread_mutex_init(&m_mutex, NULL);
239 }
240 
~Mutex()241 Mutex::~Mutex()
242 {
243     pthread_mutex_destroy(&m_mutex);
244 }
245 
lock()246 void Mutex::lock()
247 {
248     int result = pthread_mutex_lock(&m_mutex);
249     ASSERT_UNUSED(result, !result);
250 }
251 
tryLock()252 bool Mutex::tryLock()
253 {
254     int result = pthread_mutex_trylock(&m_mutex);
255 
256     if (result == 0)
257         return true;
258     if (result == EBUSY)
259         return false;
260 
261     ASSERT_NOT_REACHED();
262     return false;
263 }
264 
unlock()265 void Mutex::unlock()
266 {
267     int result = pthread_mutex_unlock(&m_mutex);
268     ASSERT_UNUSED(result, !result);
269 }
270 
271 #if HAVE(PTHREAD_RWLOCK)
272 
ReadWriteLock()273 ReadWriteLock::ReadWriteLock()
274 {
275     pthread_rwlock_init(&m_readWriteLock, NULL);
276 }
277 
~ReadWriteLock()278 ReadWriteLock::~ReadWriteLock()
279 {
280     pthread_rwlock_destroy(&m_readWriteLock);
281 }
282 
readLock()283 void ReadWriteLock::readLock()
284 {
285     int result = pthread_rwlock_rdlock(&m_readWriteLock);
286     ASSERT_UNUSED(result, !result);
287 }
288 
tryReadLock()289 bool ReadWriteLock::tryReadLock()
290 {
291     int result = pthread_rwlock_tryrdlock(&m_readWriteLock);
292 
293     if (result == 0)
294         return true;
295     if (result == EBUSY || result == EAGAIN)
296         return false;
297 
298     ASSERT_NOT_REACHED();
299     return false;
300 }
301 
writeLock()302 void ReadWriteLock::writeLock()
303 {
304     int result = pthread_rwlock_wrlock(&m_readWriteLock);
305     ASSERT_UNUSED(result, !result);
306 }
307 
tryWriteLock()308 bool ReadWriteLock::tryWriteLock()
309 {
310     int result = pthread_rwlock_trywrlock(&m_readWriteLock);
311 
312     if (result == 0)
313         return true;
314     if (result == EBUSY || result == EAGAIN)
315         return false;
316 
317     ASSERT_NOT_REACHED();
318     return false;
319 }
320 
unlock()321 void ReadWriteLock::unlock()
322 {
323     int result = pthread_rwlock_unlock(&m_readWriteLock);
324     ASSERT_UNUSED(result, !result);
325 }
326 #endif  // HAVE(PTHREAD_RWLOCK)
327 
ThreadCondition()328 ThreadCondition::ThreadCondition()
329 {
330     pthread_cond_init(&m_condition, NULL);
331 }
332 
~ThreadCondition()333 ThreadCondition::~ThreadCondition()
334 {
335     pthread_cond_destroy(&m_condition);
336 }
337 
wait(Mutex & mutex)338 void ThreadCondition::wait(Mutex& mutex)
339 {
340     int result = pthread_cond_wait(&m_condition, &mutex.impl());
341     ASSERT_UNUSED(result, !result);
342 }
343 
timedWait(Mutex & mutex,double absoluteTime)344 bool ThreadCondition::timedWait(Mutex& mutex, double absoluteTime)
345 {
346     if (absoluteTime < currentTime())
347         return false;
348 
349     if (absoluteTime > INT_MAX) {
350         wait(mutex);
351         return true;
352     }
353 
354     int timeSeconds = static_cast<int>(absoluteTime);
355     int timeNanoseconds = static_cast<int>((absoluteTime - timeSeconds) * 1E9);
356 
357     timespec targetTime;
358     targetTime.tv_sec = timeSeconds;
359     targetTime.tv_nsec = timeNanoseconds;
360 
361     return pthread_cond_timedwait(&m_condition, &mutex.impl(), &targetTime) == 0;
362 }
363 
signal()364 void ThreadCondition::signal()
365 {
366     int result = pthread_cond_signal(&m_condition);
367     ASSERT_UNUSED(result, !result);
368 }
369 
broadcast()370 void ThreadCondition::broadcast()
371 {
372     int result = pthread_cond_broadcast(&m_condition);
373     ASSERT_UNUSED(result, !result);
374 }
375 
376 } // namespace WTF
377 
378 #endif // USE(PTHREADS)
379