ThreadingPthreads.cpp 9.28 KB
Newer Older
andersca's avatar
andersca committed
1
/*
2
 * Copyright (C) 2007, 2009 Apple Inc. All rights reserved.
3
 * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com)
andersca's avatar
andersca committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer. 
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution. 
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
29

andersca's avatar
andersca committed
30
31
32
#include "config.h"
#include "Threading.h"

33
34
#if USE(PTHREADS)

35
#include "CurrentTime.h"
ap@webkit.org's avatar
ap@webkit.org committed
36
37
#include "HashMap.h"
#include "MainThread.h"
38
#include "RandomNumberSeed.h"
39
40
#include "StdLibExtras.h"
#include "UnusedParam.h"
bdash's avatar
bdash committed
41
#include <errno.h>
42
43

#if !COMPILER(MSVC)
44
#include <limits.h>
45
#include <sys/time.h>
46
#endif
bdash's avatar
bdash committed
47

48
49
50
51
#if PLATFORM(ANDROID)
#include "jni_utility.h"
#endif

52
namespace WTF {
andersca's avatar
andersca committed
53

dimich@chromium.org's avatar
dimich@chromium.org committed
54
typedef HashMap<ThreadIdentifier, pthread_t> ThreadMap;
55

56
static Mutex* atomicallyInitializedStaticMutex;
ap@webkit.org's avatar
ap@webkit.org committed
57

58
#if !PLATFORM(DARWIN) || PLATFORM(CHROMIUM)
ap@webkit.org's avatar
ap@webkit.org committed
59
60
static ThreadIdentifier mainThreadIdentifier; // The thread that was the first to call initializeThreading(), which must be the main thread.
#endif
aroben@apple.com's avatar
aroben@apple.com committed
61

dimich@chromium.org's avatar
dimich@chromium.org committed
62
63
64
65
66
67
static Mutex& threadMapMutex()
{
    DEFINE_STATIC_LOCAL(Mutex, mutex, ());
    return mutex;
}

ap@webkit.org's avatar
ap@webkit.org committed
68
69
70
71
void initializeThreading()
{
    if (!atomicallyInitializedStaticMutex) {
        atomicallyInitializedStaticMutex = new Mutex;
dimich@chromium.org's avatar
dimich@chromium.org committed
72
        threadMapMutex();
73
        initializeRandomNumberGenerator();
74
#if !PLATFORM(DARWIN) || PLATFORM(CHROMIUM)
aroben@apple.com's avatar
aroben@apple.com committed
75
        mainThreadIdentifier = currentThread();
ap@webkit.org's avatar
ap@webkit.org committed
76
77
#endif
        initializeMainThread();
ap@webkit.org's avatar
ap@webkit.org committed
78
79
80
    }
}

81
82
83
84
85
86
87
88
89
90
91
void lockAtomicallyInitializedStaticMutex()
{
    ASSERT(atomicallyInitializedStaticMutex);
    atomicallyInitializedStaticMutex->lock();
}

void unlockAtomicallyInitializedStaticMutex()
{
    atomicallyInitializedStaticMutex->unlock();
}

dimich@chromium.org's avatar
dimich@chromium.org committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
static ThreadMap& threadMap()
{
    DEFINE_STATIC_LOCAL(ThreadMap, map, ());
    return map;
}

static ThreadIdentifier identifierByPthreadHandle(const pthread_t& pthreadHandle)
{
    MutexLocker locker(threadMapMutex());

    ThreadMap::iterator i = threadMap().begin();
    for (; i != threadMap().end(); ++i) {
        if (pthread_equal(i->second, pthreadHandle))
            return i->first;
    }

    return 0;
}

static ThreadIdentifier establishIdentifierForPthreadHandle(pthread_t& pthreadHandle)
{
    ASSERT(!identifierByPthreadHandle(pthreadHandle));

    MutexLocker locker(threadMapMutex());

    static ThreadIdentifier identifierCount = 1;

    threadMap().add(identifierCount, pthreadHandle);

    return identifierCount++;
}

static pthread_t pthreadHandleForIdentifier(ThreadIdentifier id)
{
    MutexLocker locker(threadMapMutex());

    return threadMap().get(id);
}

static void clearPthreadHandleForIdentifier(ThreadIdentifier id)
{
    MutexLocker locker(threadMapMutex());

    ASSERT(threadMap().contains(id));

    threadMap().remove(id);
}

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#if PLATFORM(ANDROID)
// On the Android platform, threads must be registered with the VM before they run.
struct ThreadData {
    ThreadFunction entryPoint;
    void* arg;
};

static void* runThreadWithRegistration(void* arg)
{
    ThreadData* data = static_cast<ThreadData*>(arg);
    JavaVM* vm = JSC::Bindings::getJavaVM();
    JNIEnv* env;
    void* ret = 0;
    if (vm->AttachCurrentThread(&env, 0) == JNI_OK) {
        ret = data->entryPoint(data->arg);
        vm->DetachCurrentThread();
    }
    delete data;
    return ret;
}

ThreadIdentifier createThreadInternal(ThreadFunction entryPoint, void* data, const char*)
{
    pthread_t threadHandle;
    ThreadData* threadData = new ThreadData();
    threadData->entryPoint = entryPoint;
    threadData->arg = data;

    if (pthread_create(&threadHandle, 0, runThreadWithRegistration, static_cast<void*>(threadData))) {
        LOG_ERROR("Failed to create pthread at entry point %p with data %p", entryPoint, data);
170
        delete threadData;
dimich@chromium.org's avatar
dimich@chromium.org committed
171
        return 0;
172
    }
dimich@chromium.org's avatar
dimich@chromium.org committed
173
    return establishIdentifierForPthreadHandle(threadHandle);
174
175
}
#else
176
ThreadIdentifier createThreadInternal(ThreadFunction entryPoint, void* data, const char*)
andersca's avatar
andersca committed
177
178
{
    pthread_t threadHandle;
179
    if (pthread_create(&threadHandle, 0, entryPoint, data)) {
andersca's avatar
andersca committed
180
        LOG_ERROR("Failed to create pthread at entry point %p with data %p", entryPoint, data);
dimich@chromium.org's avatar
dimich@chromium.org committed
181
        return 0;
andersca's avatar
andersca committed
182
183
    }

dimich@chromium.org's avatar
dimich@chromium.org committed
184
    return establishIdentifierForPthreadHandle(threadHandle);
andersca's avatar
andersca committed
185
}
186
#endif
andersca's avatar
andersca committed
187

188
189
void setThreadNameInternal(const char* threadName)
{
190
#if HAVE(PTHREAD_SETNAME_NP)
191
192
193
194
195
196
    pthread_setname_np(threadName);
#else
    UNUSED_PARAM(threadName);
#endif
}

andersca's avatar
andersca committed
197
198
int waitForThreadCompletion(ThreadIdentifier threadID, void** result)
{
dimich@chromium.org's avatar
dimich@chromium.org committed
199
200
201
202
    ASSERT(threadID);

    pthread_t pthreadHandle = pthreadHandleForIdentifier(threadID);

andersca's avatar
andersca committed
203
204
    int joinResult = pthread_join(pthreadHandle, result);
    if (joinResult == EDEADLK)
dimich@chromium.org's avatar
dimich@chromium.org committed
205
206
207
        LOG_ERROR("ThreadIdentifier %u was found to be deadlocked trying to quit", threadID);

    clearPthreadHandleForIdentifier(threadID);
andersca's avatar
andersca committed
208
209
210
211
212
    return joinResult;
}

void detachThread(ThreadIdentifier threadID)
{
dimich@chromium.org's avatar
dimich@chromium.org committed
213
214
215
216
    ASSERT(threadID);

    pthread_t pthreadHandle = pthreadHandleForIdentifier(threadID);

andersca's avatar
andersca committed
217
    pthread_detach(pthreadHandle);
dimich@chromium.org's avatar
dimich@chromium.org committed
218
219

    clearPthreadHandleForIdentifier(threadID);
andersca's avatar
andersca committed
220
221
}

222
223
ThreadIdentifier currentThread()
{
dimich@chromium.org's avatar
dimich@chromium.org committed
224
225
226
227
    pthread_t currentThread = pthread_self();
    if (ThreadIdentifier id = identifierByPthreadHandle(currentThread))
        return id;
    return establishIdentifierForPthreadHandle(currentThread);
228
229
}

aroben@apple.com's avatar
aroben@apple.com committed
230
231
bool isMainThread()
{
232
#if PLATFORM(DARWIN) && !PLATFORM(CHROMIUM)
ap@webkit.org's avatar
ap@webkit.org committed
233
234
    return pthread_main_np();
#else
aroben@apple.com's avatar
aroben@apple.com committed
235
    return currentThread() == mainThreadIdentifier;
ap@webkit.org's avatar
ap@webkit.org committed
236
#endif
aroben@apple.com's avatar
aroben@apple.com committed
237
238
}

andersca's avatar
andersca committed
239
240
241
242
243
244
245
246
247
248
249
250
Mutex::Mutex()
{
    pthread_mutex_init(&m_mutex, NULL);
}

Mutex::~Mutex()
{
    pthread_mutex_destroy(&m_mutex);
}

void Mutex::lock()
{
ap@webkit.org's avatar
ap@webkit.org committed
251
252
    int result = pthread_mutex_lock(&m_mutex);
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
253
}
dimich@chromium.org's avatar
dimich@chromium.org committed
254

andersca's avatar
andersca committed
255
256
257
bool Mutex::tryLock()
{
    int result = pthread_mutex_trylock(&m_mutex);
dimich@chromium.org's avatar
dimich@chromium.org committed
258

andersca's avatar
andersca committed
259
260
    if (result == 0)
        return true;
ap@webkit.org's avatar
ap@webkit.org committed
261
    if (result == EBUSY)
andersca's avatar
andersca committed
262
263
        return false;

ap@webkit.org's avatar
ap@webkit.org committed
264
    ASSERT_NOT_REACHED();
andersca's avatar
andersca committed
265
266
267
268
269
    return false;
}

void Mutex::unlock()
{
ap@webkit.org's avatar
ap@webkit.org committed
270
271
    int result = pthread_mutex_unlock(&m_mutex);
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
272
}
273

274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328

ReadWriteLock::ReadWriteLock()
{
    pthread_rwlock_init(&m_readWriteLock, NULL);
}

ReadWriteLock::~ReadWriteLock()
{
    pthread_rwlock_destroy(&m_readWriteLock);
}

void ReadWriteLock::readLock()
{
    int result = pthread_rwlock_rdlock(&m_readWriteLock);
    ASSERT_UNUSED(result, !result);
}

bool ReadWriteLock::tryReadLock()
{
    int result = pthread_rwlock_tryrdlock(&m_readWriteLock);

    if (result == 0)
        return true;
    if (result == EBUSY || result == EAGAIN)
        return false;

    ASSERT_NOT_REACHED();
    return false;
}

void ReadWriteLock::writeLock()
{
    int result = pthread_rwlock_wrlock(&m_readWriteLock);
    ASSERT_UNUSED(result, !result);
}

bool ReadWriteLock::tryWriteLock()
{
    int result = pthread_rwlock_trywrlock(&m_readWriteLock);

    if (result == 0)
        return true;
    if (result == EBUSY || result == EAGAIN)
        return false;

    ASSERT_NOT_REACHED();
    return false;
}

void ReadWriteLock::unlock()
{
    int result = pthread_rwlock_unlock(&m_readWriteLock);
    ASSERT_UNUSED(result, !result);
}

andersca's avatar
andersca committed
329
330
331
332
333
334
335
336
337
338
339
340
ThreadCondition::ThreadCondition()
{ 
    pthread_cond_init(&m_condition, NULL);
}

ThreadCondition::~ThreadCondition()
{
    pthread_cond_destroy(&m_condition);
}
    
void ThreadCondition::wait(Mutex& mutex)
{
ap@webkit.org's avatar
ap@webkit.org committed
341
342
    int result = pthread_cond_wait(&m_condition, &mutex.impl());
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
343
}
beidson@apple.com's avatar
beidson@apple.com committed
344

345
bool ThreadCondition::timedWait(Mutex& mutex, double absoluteTime)
beidson@apple.com's avatar
beidson@apple.com committed
346
{
347
348
349
350
    if (absoluteTime < currentTime())
        return false;

    if (absoluteTime > INT_MAX) {
beidson@apple.com's avatar
beidson@apple.com committed
351
352
353
        wait(mutex);
        return true;
    }
354

355
356
    int timeSeconds = static_cast<int>(absoluteTime);
    int timeNanoseconds = static_cast<int>((absoluteTime - timeSeconds) * 1E9);
357

beidson@apple.com's avatar
beidson@apple.com committed
358
    timespec targetTime;
359
360
    targetTime.tv_sec = timeSeconds;
    targetTime.tv_nsec = timeNanoseconds;
beidson@apple.com's avatar
beidson@apple.com committed
361
362
363
364

    return pthread_cond_timedwait(&m_condition, &mutex.impl(), &targetTime) == 0;
}

andersca's avatar
andersca committed
365
366
void ThreadCondition::signal()
{
ap@webkit.org's avatar
ap@webkit.org committed
367
368
    int result = pthread_cond_signal(&m_condition);
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
369
370
371
372
}

void ThreadCondition::broadcast()
{
ap@webkit.org's avatar
ap@webkit.org committed
373
374
    int result = pthread_cond_broadcast(&m_condition);
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
375
}
dimich@chromium.org's avatar
dimich@chromium.org committed
376

377
} // namespace WTF
378
379

#endif // USE(PTHREADS)