1 /*
2 * Copyright (c) 2023, Meta
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <errno.h>
8 #include <threads.h>
9
10 #include <zephyr/kernel.h>
11 #include <zephyr/posix/pthread.h>
12 #include <zephyr/posix/sched.h>
13
14 struct thrd_trampoline_arg {
15 thrd_start_t func;
16 void *arg;
17 };
18
thrd_create(thrd_t * thr,thrd_start_t func,void * arg)19 int thrd_create(thrd_t *thr, thrd_start_t func, void *arg)
20 {
21 typedef void *(*pthread_func_t)(void *arg);
22
23 pthread_func_t pfunc = (pthread_func_t)func;
24
25 switch (pthread_create(thr, NULL, pfunc, arg)) {
26 case 0:
27 return thrd_success;
28 case EAGAIN:
29 return thrd_nomem;
30 default:
31 return thrd_error;
32 }
33 }
34
thrd_equal(thrd_t lhs,thrd_t rhs)35 int thrd_equal(thrd_t lhs, thrd_t rhs)
36 {
37 return pthread_equal(lhs, rhs);
38 }
39
thrd_current(void)40 thrd_t thrd_current(void)
41 {
42 return pthread_self();
43 }
44
thrd_sleep(const struct timespec * duration,struct timespec * remaining)45 int thrd_sleep(const struct timespec *duration, struct timespec *remaining)
46 {
47 return nanosleep(duration, remaining);
48 }
49
thrd_yield(void)50 void thrd_yield(void)
51 {
52 (void)sched_yield();
53 }
54
thrd_exit(int res)55 FUNC_NORETURN void thrd_exit(int res)
56 {
57 pthread_exit(INT_TO_POINTER(res));
58
59 CODE_UNREACHABLE;
60 }
61
thrd_detach(thrd_t thr)62 int thrd_detach(thrd_t thr)
63 {
64 switch (pthread_detach(thr)) {
65 case 0:
66 return thrd_success;
67 default:
68 return thrd_error;
69 }
70 }
71
thrd_join(thrd_t thr,int * res)72 int thrd_join(thrd_t thr, int *res)
73 {
74 void *ret;
75
76 switch (pthread_join(thr, &ret)) {
77 case 0:
78 if (res != NULL) {
79 *res = POINTER_TO_INT(ret);
80 }
81 return thrd_success;
82 default:
83 return thrd_error;
84 }
85 }
86