ort_openrouter_cli/common/
thread.rs

1//! ort: Open Router CLI
2//! https://github.com/grahamking/ort
3//!
4//! MIT License
5//! Copyright (c) 2025 Graham King
6//!
7
8use core::ffi::c_void;
9use core::mem;
10use core::ptr;
11
12use crate::{ErrorKind, OrtResult, libc, ort_error};
13
14// Linux default (libpthread) is 8 MiB. We don't need that much.
15const STACK_SIZE: usize = 1024 * 1024; // 1 MiB
16const GUARD_SIZE: usize = 64 * 1024; // 64 KiB
17
18/// Start a thread.
19/// Returns 0 on success, 1 if allocating stack space failed, 2 if clone failed.
20/// # Safety
21/// TODO
22pub unsafe fn spawn(
23    thread_func: extern "C" fn(*mut c_void) -> *mut c_void,
24    arg: *mut c_void,
25) -> OrtResult<libc::pthread_t> {
26    //
27    // Stack
28    // Memory returned by mmap is aligned.
29    // We never free it, when the threads are done the whole program is usually done.
30    //
31
32    let stack_base = unsafe {
33        libc::mmap(
34            ptr::null_mut(),
35            STACK_SIZE + GUARD_SIZE,
36            libc::PROT_READ | libc::PROT_WRITE,
37            libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_STACK,
38            -1,
39            0,
40        )
41    };
42    if stack_base.is_null() {
43        return Err(ort_error(ErrorKind::ThreadStackAllocFailed, ""));
44    }
45    unsafe { libc::mprotect(stack_base, GUARD_SIZE, libc::PROT_NONE) };
46
47    //
48    // pthread
49    //
50
51    let mut thread_id: libc::pthread_t = 0;
52    let mut attr: libc::pthread_attr_t = unsafe { mem::zeroed() };
53
54    let rc = unsafe {
55        libc::pthread_attr_init(&mut attr);
56        // Skip the guard page when handing stack to pthreads.
57        libc::pthread_attr_setstack(&mut attr, stack_base.add(GUARD_SIZE), STACK_SIZE);
58        let rc = libc::pthread_create(&mut thread_id, &attr, thread_func, arg);
59        libc::pthread_attr_destroy(&mut attr);
60        rc
61    };
62    if rc != 0 {
63        Err(ort_error(ErrorKind::ThreadSpawnFailed, ""))
64    } else {
65        Ok(thread_id)
66    }
67}