Skip to main content

ax_libc/
pthread.rs

1use core::ffi::{c_int, c_void};
2
3use ax_posix_api as api;
4
5use crate::ctypes;
6
7fn pthread_result(ret: c_int) -> c_int {
8    if ret < 0 { -ret } else { ret }
9}
10
11/// Returns the `pthread` struct of current thread.
12#[unsafe(no_mangle)]
13pub unsafe extern "C" fn pthread_self() -> ctypes::pthread_t {
14    api::sys_pthread_self()
15}
16
17/// Create a new thread with the given entry point and argument.
18///
19/// If successful, it stores the pointer to the newly created `struct __pthread`
20/// in `res` and returns 0.
21#[unsafe(no_mangle)]
22pub unsafe extern "C" fn pthread_create(
23    res: *mut ctypes::pthread_t,
24    attr: *const ctypes::pthread_attr_t,
25    start_routine: extern "C" fn(arg: *mut c_void) -> *mut c_void,
26    arg: *mut c_void,
27) -> c_int {
28    unsafe { pthread_result(api::sys_pthread_create(res, attr, start_routine, arg)) }
29}
30
31/// Exits the current thread. The value `retval` will be returned to the joiner.
32#[unsafe(no_mangle)]
33pub unsafe extern "C" fn pthread_exit(retval: *mut c_void) -> ! {
34    api::sys_pthread_exit(retval)
35}
36
37/// Waits for the given thread to exit, and stores the return value in `retval`.
38#[unsafe(no_mangle)]
39pub unsafe extern "C" fn pthread_join(
40    thread: ctypes::pthread_t,
41    retval: *mut *mut c_void,
42) -> c_int {
43    unsafe { pthread_result(api::sys_pthread_join(thread, retval)) }
44}
45
46/// Marks a joinable thread detached so it is reclaimed automatically.
47#[unsafe(no_mangle)]
48pub unsafe extern "C" fn pthread_detach(thread: ctypes::pthread_t) -> c_int {
49    pthread_result(api::sys_pthread_detach(thread))
50}
51
52/// Initialize a mutex.
53#[unsafe(no_mangle)]
54pub unsafe extern "C" fn pthread_mutex_init(
55    mutex: *mut ctypes::pthread_mutex_t,
56    attr: *const ctypes::pthread_mutexattr_t,
57) -> c_int {
58    pthread_result(api::sys_pthread_mutex_init(mutex, attr))
59}
60
61/// Lock the given mutex.
62#[unsafe(no_mangle)]
63pub unsafe extern "C" fn pthread_mutex_lock(mutex: *mut ctypes::pthread_mutex_t) -> c_int {
64    pthread_result(api::sys_pthread_mutex_lock(mutex))
65}
66
67/// Try locking the given mutex.
68#[unsafe(no_mangle)]
69pub unsafe extern "C" fn pthread_mutex_trylock(mutex: *mut ctypes::pthread_mutex_t) -> c_int {
70    pthread_result(api::sys_pthread_mutex_trylock(mutex))
71}
72
73/// Unlock the given mutex.
74#[unsafe(no_mangle)]
75pub unsafe extern "C" fn pthread_mutex_unlock(mutex: *mut ctypes::pthread_mutex_t) -> c_int {
76    pthread_result(api::sys_pthread_mutex_unlock(mutex))
77}
78
79/// Destroy the given mutex.
80#[unsafe(no_mangle)]
81pub unsafe extern "C" fn pthread_mutex_destroy(mutex: *mut ctypes::pthread_mutex_t) -> c_int {
82    pthread_result(api::sys_pthread_mutex_destroy(mutex))
83}