src/platform/posix/threading.h (view raw)
1/* Copyright (c) 2013-2015 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#ifndef POSIX_THREADING_H
7#define POSIX_THREADING_H
8
9#include "util/common.h"
10
11#include <pthread.h>
12#include <sys/time.h>
13#ifdef __FreeBSD__
14#include <pthread_np.h>
15#endif
16
17#define THREAD_ENTRY void*
18typedef THREAD_ENTRY (*ThreadEntry)(void*);
19
20typedef pthread_t Thread;
21typedef pthread_mutex_t Mutex;
22typedef pthread_cond_t Condition;
23
24static inline int MutexInit(Mutex* mutex) {
25 return pthread_mutex_init(mutex, 0);
26}
27
28static inline int MutexDeinit(Mutex* mutex) {
29 return pthread_mutex_destroy(mutex);
30}
31
32static inline int MutexLock(Mutex* mutex) {
33 return pthread_mutex_lock(mutex);
34}
35
36static inline int MutexUnlock(Mutex* mutex) {
37 return pthread_mutex_unlock(mutex);
38}
39
40static inline int ConditionInit(Condition* cond) {
41 return pthread_cond_init(cond, 0);
42}
43
44static inline int ConditionDeinit(Condition* cond) {
45 return pthread_cond_destroy(cond);
46}
47
48static inline int ConditionWait(Condition* cond, Mutex* mutex) {
49 return pthread_cond_wait(cond, mutex);
50}
51
52static inline int ConditionWaitTimed(Condition* cond, Mutex* mutex, int32_t timeoutMs) {
53 struct timespec ts;
54 struct timeval tv;
55
56 gettimeofday(&tv, 0);
57 ts.tv_sec = tv.tv_sec;
58 ts.tv_nsec = (tv.tv_usec + timeoutMs * 1000L) * 1000L;
59 if (ts.tv_nsec >= 1000000000L) {
60 ts.tv_nsec -= 1000000000L;
61 ++ts.tv_sec;
62 }
63
64 return pthread_cond_timedwait(cond, mutex, &ts);
65}
66
67static inline int ConditionWake(Condition* cond) {
68 return pthread_cond_broadcast(cond);
69}
70
71static inline int ThreadCreate(Thread* thread, ThreadEntry entry, void* context) {
72 return pthread_create(thread, 0, entry, context);
73}
74
75static inline int ThreadJoin(Thread thread) {
76 return pthread_join(thread, 0);
77}
78
79static inline int ThreadSetName(const char* name) {
80#ifdef __APPLE__
81 return pthread_setname_np(name);
82#elif defined(__FreeBSD__) || defined(__OpenBSD__)
83 pthread_set_name_np(pthread_self(), name);
84 return 0;
85#else
86 return pthread_setname_np(pthread_self(), name);
87#endif
88}
89
90#endif