ThreadingPthreads.cpp 6.94 KB
Newer Older
andersca's avatar
andersca committed
1
2
/*
 * Copyright (C) 2007 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
29
30
31
 *
 * 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.
 */
#include "config.h"
#include "Threading.h"

32
33
#include "StdLibExtras.h"

34
35
#if USE(PTHREADS)

36
#include "CurrentTime.h"
ap@webkit.org's avatar
ap@webkit.org committed
37
38
#include "HashMap.h"
#include "MainThread.h"
39
#include "RandomNumberSeed.h"
andersca's avatar
andersca committed
40

bdash's avatar
bdash committed
41
#include <errno.h>
42
#include <limits.h>
43
#include <sys/time.h>
bdash's avatar
bdash committed
44

45
namespace WTF {
andersca's avatar
andersca committed
46

47
48
typedef HashMap<ThreadIdentifier, pthread_t> ThreadMap;

49
static Mutex* atomicallyInitializedStaticMutex;
ap@webkit.org's avatar
ap@webkit.org committed
50

51
#if !PLATFORM(DARWIN) || PLATFORM(CHROMIUM)
ap@webkit.org's avatar
ap@webkit.org committed
52
53
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
54

ap@webkit.org's avatar
ap@webkit.org committed
55
56
static Mutex& threadMapMutex()
{
57
    DEFINE_STATIC_LOCAL(Mutex, mutex, ());
ap@webkit.org's avatar
ap@webkit.org committed
58
59
60
    return mutex;
}

ap@webkit.org's avatar
ap@webkit.org committed
61
62
63
64
void initializeThreading()
{
    if (!atomicallyInitializedStaticMutex) {
        atomicallyInitializedStaticMutex = new Mutex;
ap@webkit.org's avatar
ap@webkit.org committed
65
        threadMapMutex();
66
        initializeRandomNumberGenerator();
67
#if !PLATFORM(DARWIN) || PLATFORM(CHROMIUM)
aroben@apple.com's avatar
aroben@apple.com committed
68
        mainThreadIdentifier = currentThread();
ap@webkit.org's avatar
ap@webkit.org committed
69
70
#endif
        initializeMainThread();
ap@webkit.org's avatar
ap@webkit.org committed
71
72
73
    }
}

74
75
76
77
78
79
80
81
82
83
84
void lockAtomicallyInitializedStaticMutex()
{
    ASSERT(atomicallyInitializedStaticMutex);
    atomicallyInitializedStaticMutex->lock();
}

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

85
static ThreadMap& threadMap()
andersca's avatar
andersca committed
86
{
87
    DEFINE_STATIC_LOCAL(ThreadMap, map, ());
andersca's avatar
andersca committed
88
89
90
    return map;
}

91
92
93
94
static ThreadIdentifier identifierByPthreadHandle(const pthread_t& pthreadHandle)
{
    MutexLocker locker(threadMapMutex());

95
    ThreadMap::iterator i = threadMap().begin();
96
97
98
99
100
101
102
103
    for (; i != threadMap().end(); ++i) {
        if (pthread_equal(i->second, pthreadHandle))
            return i->first;
    }

    return 0;
}

104
105
106
107
108
109
110
111
112
113
114
115
116
static ThreadIdentifier establishIdentifierForPthreadHandle(pthread_t& pthreadHandle)
{
    ASSERT(!identifierByPthreadHandle(pthreadHandle));

    MutexLocker locker(threadMapMutex());

    static ThreadIdentifier identifierCount = 1;

    threadMap().add(identifierCount, pthreadHandle);
    
    return identifierCount++;
}

andersca's avatar
andersca committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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);
}

133
ThreadIdentifier createThreadInternal(ThreadFunction entryPoint, void* data, const char*)
andersca's avatar
andersca committed
134
135
136
137
138
139
140
{
    pthread_t threadHandle;
    if (pthread_create(&threadHandle, NULL, entryPoint, data)) {
        LOG_ERROR("Failed to create pthread at entry point %p with data %p", entryPoint, data);
        return 0;
    }

141
    return establishIdentifierForPthreadHandle(threadHandle);
andersca's avatar
andersca committed
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
}

int waitForThreadCompletion(ThreadIdentifier threadID, void** result)
{
    ASSERT(threadID);
    
    pthread_t pthreadHandle = pthreadHandleForIdentifier(threadID);
 
    int joinResult = pthread_join(pthreadHandle, result);
    if (joinResult == EDEADLK)
        LOG_ERROR("ThreadIdentifier %u was found to be deadlocked trying to quit", threadID);
        
    clearPthreadHandleForIdentifier(threadID);
    return joinResult;
}

void detachThread(ThreadIdentifier threadID)
{
    ASSERT(threadID);
    
    pthread_t pthreadHandle = pthreadHandleForIdentifier(threadID);
    
    pthread_detach(pthreadHandle);
    
    clearPthreadHandleForIdentifier(threadID);
}

169
170
171
172
173
174
175
176
ThreadIdentifier currentThread()
{
    pthread_t currentThread = pthread_self();
    if (ThreadIdentifier id = identifierByPthreadHandle(currentThread))
        return id;
    return establishIdentifierForPthreadHandle(currentThread);
}

aroben@apple.com's avatar
aroben@apple.com committed
177
178
bool isMainThread()
{
179
#if PLATFORM(DARWIN) && !PLATFORM(CHROMIUM)
ap@webkit.org's avatar
ap@webkit.org committed
180
181
    return pthread_main_np();
#else
aroben@apple.com's avatar
aroben@apple.com committed
182
    return currentThread() == mainThreadIdentifier;
ap@webkit.org's avatar
ap@webkit.org committed
183
#endif
aroben@apple.com's avatar
aroben@apple.com committed
184
185
}

andersca's avatar
andersca committed
186
187
188
189
190
191
192
193
194
195
196
197
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
198
199
    int result = pthread_mutex_lock(&m_mutex);
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
200
201
202
203
204
205
206
207
}
    
bool Mutex::tryLock()
{
    int result = pthread_mutex_trylock(&m_mutex);
    
    if (result == 0)
        return true;
ap@webkit.org's avatar
ap@webkit.org committed
208
    if (result == EBUSY)
andersca's avatar
andersca committed
209
210
        return false;

ap@webkit.org's avatar
ap@webkit.org committed
211
    ASSERT_NOT_REACHED();
andersca's avatar
andersca committed
212
213
214
215
216
    return false;
}

void Mutex::unlock()
{
ap@webkit.org's avatar
ap@webkit.org committed
217
218
    int result = pthread_mutex_unlock(&m_mutex);
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
219
}
220

andersca's avatar
andersca committed
221
222
223
224
225
226
227
228
229
230
231
232
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
233
234
    int result = pthread_cond_wait(&m_condition, &mutex.impl());
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
235
}
beidson@apple.com's avatar
beidson@apple.com committed
236

237
bool ThreadCondition::timedWait(Mutex& mutex, double absoluteTime)
beidson@apple.com's avatar
beidson@apple.com committed
238
{
239
240
241
242
    if (absoluteTime < currentTime())
        return false;

    if (absoluteTime > INT_MAX) {
beidson@apple.com's avatar
beidson@apple.com committed
243
244
245
        wait(mutex);
        return true;
    }
246

247
248
    int timeSeconds = static_cast<int>(absoluteTime);
    int timeNanoseconds = static_cast<int>((absoluteTime - timeSeconds) * 1E9);
249

beidson@apple.com's avatar
beidson@apple.com committed
250
    timespec targetTime;
251
252
    targetTime.tv_sec = timeSeconds;
    targetTime.tv_nsec = timeNanoseconds;
beidson@apple.com's avatar
beidson@apple.com committed
253
254
255
256

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

andersca's avatar
andersca committed
257
258
void ThreadCondition::signal()
{
ap@webkit.org's avatar
ap@webkit.org committed
259
260
    int result = pthread_cond_signal(&m_condition);
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
261
262
263
264
}

void ThreadCondition::broadcast()
{
ap@webkit.org's avatar
ap@webkit.org committed
265
266
    int result = pthread_cond_broadcast(&m_condition);
    ASSERT_UNUSED(result, !result);
andersca's avatar
andersca committed
267
268
}
    
269
} // namespace WTF
270
271

#endif // USE(PTHREADS)