-
Notifications
You must be signed in to change notification settings - Fork 4
/
u_threads_pthreads.c
152 lines (121 loc) · 2.44 KB
/
u_threads_pthreads.c
1
2
3
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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
140
141
142
143
144
145
146
147
148
149
150
151
152
#include <time.h> /* nanosleep */
#include <errno.h>
#include "u_threads.h"
static void* thread_func_wrapper(void *arg)
{
U_Thread *th = arg;
th->func(th->arg);
return 0;
}
int U_thread_create(U_Thread *th, void (*func)(void *), void *arg)
{
int ret;
th->func = func;
th->arg = arg;
ret = pthread_create(&th->thread, NULL, thread_func_wrapper, th);
if (ret != 0)
return 0;
return 1;
}
int U_thread_join(U_Thread *th)
{
int ret;
void *result;
ret = pthread_join(th->thread, &result);
if (ret != 0)
return 0;
return 1;
}
void U_thread_exit(int result)
{
(void)result;
pthread_exit(0);
}
void U_thread_msleep(unsigned long milliseconds)
{
int res;
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
do {
res = nanosleep(&ts, &ts);
} while (res && errno == EINTR);
}
int U_thread_mutex_init(U_Mutex *m)
{
if (pthread_mutex_init(&m->mutex, 0) == 0)
return 1;
return 0;
}
int U_thread_mutex_destroy(U_Mutex *m)
{
if (pthread_mutex_destroy(&m->mutex) == 0)
return 1;
return 0;
}
int U_thread_mutex_lock(U_Mutex *m)
{
if (pthread_mutex_lock(&m->mutex) == 0)
return 1;
return 0;
}
int U_thread_mutex_trylock(U_Mutex *m)
{
if (pthread_mutex_trylock(&m->mutex) == 0)
return 1;
return 0;
}
int U_thread_mutex_unlock(U_Mutex *m)
{
if (pthread_mutex_unlock(&m->mutex) == 0)
return 1;
return 0;
}
int U_thread_semaphore_init(U_Semaphore *s, unsigned initial_value)
{
#ifdef __APPLE__
s->sem = dispatch_semaphore_create((long)initial_value);
if (s->sem != 0)
return 1;
#else
int pshared;
pshared = 0;
if (sem_init(&s->sem, pshared, initial_value) == 0)
return 1;
#endif
return 0;
}
int U_thread_semaphore_destroy(U_Semaphore *s)
{
#ifdef __APPLE__
/* no destroy function?! */
return 1;
#else
if (sem_destroy(&s->sem) == 0)
return 1;
return 0;
#endif
}
int U_thread_semaphore_wait(U_Semaphore *s)
{
#ifdef __APPLE__
dispatch_semaphore_wait(s->sem, DISPATCH_TIME_FOREVER);
#else
int r;
do {
r = sem_wait(&s->sem);
} while (r == -1 && errno == EINTR);
#endif
return 1;
}
int U_thread_semaphore_post(U_Semaphore *s)
{
#ifdef __APPLE__
dispatch_semaphore_signal(s->sem);
return 1;
#else
if (sem_post(&s->sem) == 0)
return 1;
return 0;
#endif
}