PatchworkOS
Loading...
Searching...
No Matches
thrd_join.c
Go to the documentation of this file.
1#include <stdatomic.h>
2#include <stdbool.h>
3#include <stdio.h>
4#include <sys/proc.h>
5#include <threads.h>
6
9
10int thrd_join(thrd_t thr, int* res)
11{
12 _thread_t* thread = _thread_get(thr.id);
13 if (thread == NULL)
14 {
15 return thrd_error;
16 }
17
18 uint64_t expected = _THREAD_ATTACHED;
19 if (!atomic_compare_exchange_strong(&thread->state, &expected, _THREAD_JOINING))
20 {
21 if (expected == _THREAD_DETACHED)
22 {
23 return thrd_error;
24 }
25 }
26
27 uint64_t state;
28 while ((state = atomic_load(&thread->state)) != _THREAD_EXITED)
29 {
30 futex(&thread->state, state, FUTEX_WAIT, CLOCKS_NEVER);
31 }
32
33 if (res != NULL)
34 {
35 *res = thread->result;
36 }
37
38 _thread_free(thread);
39 return thrd_success;
40}
#define CLOCKS_NEVER
Definition clock_t.h:16
uint64_t futex(atomic_uint64_t *addr, uint64_t val, futex_op_t op, clock_t timeout)
System call for fast user space mutual exclusion.
Definition futex.c:6
@ FUTEX_WAIT
The futex operating for waiting until the value pointed to by addr is not equal to val.
Definition proc.h:227
#define NULL
Pointer error value.
Definition NULL.h:23
_thread_t * _thread_get(tid_t id)
Definition thread.c:72
void _thread_free(_thread_t *thread)
Definition thread.c:61
#define _THREAD_EXITED
Definition thread.h:21
#define _THREAD_JOINING
Definition thread.h:20
#define _THREAD_DETACHED
Definition thread.h:19
#define _THREAD_ATTACHED
Definition thread.h:18
#define atomic_compare_exchange_strong(object, expected, desired)
Definition stdatomic.h:278
#define atomic_load(object)
Definition stdatomic.h:288
__UINT64_TYPE__ uint64_t
Definition stdint.h:17
int result
Definition thread.h:28
atomic_uint64_t state
Definition thread.h:26
tid_t id
Definition threads.h:38
int thrd_join(thrd_t thr, int *res)
Definition thrd_join.c:10
@ thrd_success
Definition threads.h:74
@ thrd_error
Definition threads.h:76