ThreadingPthreads.cpp 7 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
#if USE(PTHREADS)

ap@webkit.org's avatar
ap@webkit.org committed
34
35
36
#include "HashMap.h"
#include "MainThread.h"
#include "MathExtras.h"
andersca's avatar
andersca committed
37

bdash's avatar
bdash committed
38
#include <errno.h>
39
#include <sys/time.h>
bdash's avatar
bdash committed
40

41
namespace WTF {
andersca's avatar
andersca committed
42

ap@webkit.org's avatar
ap@webkit.org committed
43
44
Mutex* atomicallyInitializedStaticMutex;

ap@webkit.org's avatar
ap@webkit.org committed
45
46
47
#if !PLATFORM(DARWIN)
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
48

ap@webkit.org's avatar
ap@webkit.org committed
49
50
51
52
53
54
static Mutex& threadMapMutex()
{
    static Mutex mutex;
    return mutex;
}

ap@webkit.org's avatar
ap@webkit.org committed
55
56
57
58
void initializeThreading()
{
    if (!atomicallyInitializedStaticMutex) {
        atomicallyInitializedStaticMutex = new Mutex;
ap@webkit.org's avatar
ap@webkit.org committed
59
        threadMapMutex();
ap@webkit.org's avatar
ap@webkit.org committed
60
        wtf_random_init();
ap@webkit.org's avatar
ap@webkit.org committed
61
#if !PLATFORM(DARWIN)
aroben@apple.com's avatar
aroben@apple.com committed
62
        mainThreadIdentifier = currentThread();
ap@webkit.org's avatar
ap@webkit.org committed
63
64
#endif
        initializeMainThread();
ap@webkit.org's avatar
ap@webkit.org committed
65
66
67
    }
}

andersca's avatar
andersca committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
static HashMap<ThreadIdentifier, pthread_t>& threadMap()
{
    static HashMap<ThreadIdentifier, pthread_t> map;
    return map;
}

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

    static ThreadIdentifier identifierCount = 1;

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

85
86
87
88
89
90
91
92
93
94
95
96
97
static ThreadIdentifier identifierByPthreadHandle(const pthread_t& pthreadHandle)
{
    MutexLocker locker(threadMapMutex());

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

    return 0;
}

andersca's avatar
andersca committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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);
}

114
ThreadIdentifier createThread(ThreadFunction entryPoint, void* data, const char*)
andersca's avatar
andersca committed
115
116
117
118
119
120
121
122
123
124
125
{
    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;
    }

    ThreadIdentifier threadID = establishIdentifierForPthreadHandle(threadHandle);
    return threadID;
}

126
127
128
129
130
131
132
133
134
#if PLATFORM(MAC)
// This function is deprecated but needs to be kept around for backward
// compatibility. Use the 3-argument version of createThread above instead.
ThreadIdentifier createThread(ThreadFunction entryPoint, void* data)
{
    return createThread(entryPoint, data, 0);
}
#endif

andersca's avatar
andersca committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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);
}

160
161
162
163
164
165
166
167
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
168
169
bool isMainThread()
{
ap@webkit.org's avatar
ap@webkit.org committed
170
171
172
#if PLATFORM(DARWIN)
    return pthread_main_np();
#else
aroben@apple.com's avatar
aroben@apple.com committed
173
    return currentThread() == mainThreadIdentifier;
ap@webkit.org's avatar
ap@webkit.org committed
174
#endif
aroben@apple.com's avatar
aroben@apple.com committed
175
176
}

andersca's avatar
andersca committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
Mutex::Mutex()
{
    pthread_mutex_init(&m_mutex, NULL);
}

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

void Mutex::lock()
{
    if (pthread_mutex_lock(&m_mutex) != 0)
        ASSERT(false);
}
    
bool Mutex::tryLock()
{
    int result = pthread_mutex_trylock(&m_mutex);
    
    if (result == 0)
        return true;
    else if (result == EBUSY)
        return false;

    ASSERT(false);
    return false;
}

void Mutex::unlock()
{
    if (pthread_mutex_unlock(&m_mutex) != 0)
        ASSERT(false);
}
                
ThreadCondition::ThreadCondition()
{ 
    pthread_cond_init(&m_condition, NULL);
}

ThreadCondition::~ThreadCondition()
{
    pthread_cond_destroy(&m_condition);
}
    
void ThreadCondition::wait(Mutex& mutex)
{
darin's avatar
darin committed
224
    if (pthread_cond_wait(&m_condition, &mutex.impl()) != 0)
andersca's avatar
andersca committed
225
226
        ASSERT(false);
}
beidson@apple.com's avatar
beidson@apple.com committed
227

228
bool ThreadCondition::timedWait(Mutex& mutex, double secondsToWait)
beidson@apple.com's avatar
beidson@apple.com committed
229
{
230
    if (secondsToWait < 0.0) {
beidson@apple.com's avatar
beidson@apple.com committed
231
232
233
        wait(mutex);
        return true;
    }
234
235
236
237

    int intervalSeconds = static_cast<int>(secondsToWait);
    int intervalMicroseconds = static_cast<int>((secondsToWait - intervalSeconds) * 1000000.0);

beidson@apple.com's avatar
beidson@apple.com committed
238
239
240
    // Current time comes in sec/microsec
    timeval currentTime;
    gettimeofday(&currentTime, NULL);
241

beidson@apple.com's avatar
beidson@apple.com committed
242
243
244
245
246
247
248
249
250
251
252
253
    // Target time comes in sec/nanosec
    timespec targetTime;
    targetTime.tv_sec = currentTime.tv_sec + intervalSeconds;
    targetTime.tv_nsec = (currentTime.tv_usec + intervalMicroseconds) * 1000;
    if (targetTime.tv_nsec > 1000000000) {
        targetTime.tv_nsec -= 1000000000;
        targetTime.tv_sec++;
    }

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

andersca's avatar
andersca committed
254
255
256
257
258
259
260
261
262
263
264
265
void ThreadCondition::signal()
{
    if (pthread_cond_signal(&m_condition) != 0)
        ASSERT(false);
}

void ThreadCondition::broadcast()
{
    if (pthread_cond_broadcast(&m_condition) != 0)
        ASSERT(false);
}
    
266
} // namespace WTF
267
268

#endif // USE(PTHREADS)