-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread.c
105 lines (78 loc) · 1.86 KB
/
thread.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
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include "thread.h"
void mutex_destroy(Mutex *const mutex) {
int _errno = errno;
(void) pthread_mutex_destroy(mutex);
errno = _errno;
}
bool thread_init(Thread *const self,
ThreadCB func,
void *const arg) {
assert(self != NULL);
assert(func != NULL);
self->thread_valid = false;
self->cancel = false;
self->func = func;
self->arg = arg;
errno = pthread_mutex_init
(&self->cancel_mutex, NULL);
if (errno != 0)
return (false);
errno = pthread_create
(&self->thread, NULL, func, arg);
if (errno != 0) {
assert(errno != EINVAL);
mutex_destroy(&self->cancel_mutex);
return (false);
}
self->thread_valid = true;
return (true);
}
void thread_cancel(Thread *const self) {
assert(self != NULL);
if (!self->thread_valid)
return;
errno = pthread_mutex_lock
(&self->cancel_mutex);
if (errno != 0)
assert(errno != EDEADLK);
self->cancel = true;
errno = pthread_mutex_unlock
(&self->cancel_mutex);
if (errno != 0)
assert(errno != EPERM);
thread_waitout(self);
}
void thread_cancelp(Thread **const self) {
assert(self != NULL);
thread_cancel(*self);
}
void thread_waitout(Thread *const self) {
assert(self != NULL);
/* silence the warn_unused_result warning */
if (self->thread_valid && thread_result(self))
return;
else
return;
}
void *thread_result(Thread *const self) {
assert(self != NULL);
if (self->thread_valid) {
void *ret = NULL;
errno = pthread_join
(self->thread, &ret);
if (errno != 0) {
assert(errno != EDEADLK);
assert(errno != EINVAL);
assert(errno != ESRCH);
return (NULL);
}
mutex_destroy(&self->cancel_mutex);
self->thread_valid = false;
return (ret);
} else {
return (self->func(self->arg));
}
}