ort_openrouter_cli/common/
thread.rs1use core::ffi::c_void;
9use core::mem;
10use core::ptr;
11
12use crate::{ErrorKind, OrtResult, libc, ort_error};
13
14const STACK_SIZE: usize = 1024 * 1024; const GUARD_SIZE: usize = 64 * 1024; pub 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 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 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 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}