1#[cfg(not(any(
2 target_env = "newlib",
3 target_os = "l4re",
4 target_os = "emscripten",
5 target_os = "redox",
6 target_os = "hurd",
7 target_os = "aix",
8)))]
9use crate::ffi::CStr;
10use crate::mem::{self, DropGuard, ManuallyDrop};
11use crate::num::NonZero;
12#[cfg(all(target_os = "linux", target_env = "gnu"))]
13use crate::sys::weak::dlsym;
14#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto",))]
15use crate::sys::weak::weak;
16use crate::sys::{os, stack_overflow};
17use crate::thread::{ThreadInit, current};
18use crate::time::Duration;
19use crate::{cmp, io, ptr};
20#[cfg(not(any(
21 target_os = "l4re",
22 target_os = "vxworks",
23 target_os = "espidf",
24 target_os = "nuttx"
25)))]
26pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
27#[cfg(target_os = "l4re")]
28pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
29#[cfg(target_os = "vxworks")]
30pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
31#[cfg(any(target_os = "espidf", target_os = "nuttx"))]
32pub const DEFAULT_MIN_STACK_SIZE: usize = 0; pub struct Thread {
35 id: libc::pthread_t,
36}
37
38unsafe impl Send for Thread {}
41unsafe impl Sync for Thread {}
42
43impl Thread {
44 #[cfg_attr(miri, track_caller)] pub unsafe fn new(stack: usize, init: Box<ThreadInit>) -> io::Result<Thread> {
47 let data = init;
48 let mut attr: mem::MaybeUninit<libc::pthread_attr_t> = mem::MaybeUninit::uninit();
49 assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0);
50 let mut attr = DropGuard::new(&mut attr, |attr| {
51 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0)
52 });
53
54 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
55 if stack > 0 {
56 assert_eq!(
59 libc::pthread_attr_setstacksize(
60 attr.as_mut_ptr(),
61 cmp::max(stack, min_stack_size(attr.as_ptr()))
62 ),
63 0
64 );
65 }
66
67 #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
68 {
69 let stack_size = cmp::max(stack, min_stack_size(attr.as_ptr()));
70
71 match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) {
72 0 => {}
73 n => {
74 assert_eq!(n, libc::EINVAL);
75 let page_size = os::page_size();
80 let stack_size =
81 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
82
83 if libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) != 0 {
87 return Err(io::const_error!(
88 io::ErrorKind::InvalidInput,
89 "invalid stack size"
90 ));
91 }
92 }
93 };
94 }
95
96 let data = Box::into_raw(data);
97 let mut native: libc::pthread_t = mem::zeroed();
98 let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, data as *mut _);
99 return if ret == 0 {
100 Ok(Thread { id: native })
101 } else {
102 drop(Box::from_raw(data));
105 Err(io::Error::from_raw_os_error(ret))
106 };
107
108 extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
109 unsafe {
110 let init = Box::from_raw(data as *mut ThreadInit);
112 let rust_start = init.init();
113
114 let thread = current();
117 let _handler = stack_overflow::Handler::new(thread.name().map(Box::from));
118
119 rust_start();
120 }
121 ptr::null_mut()
122 }
123 }
124
125 pub fn join(self) {
126 let id = self.into_id();
127 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
128 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
129 }
130
131 pub fn id(&self) -> libc::pthread_t {
132 self.id
133 }
134
135 pub fn into_id(self) -> libc::pthread_t {
136 ManuallyDrop::new(self).id
137 }
138}
139
140impl Drop for Thread {
141 fn drop(&mut self) {
142 let ret = unsafe { libc::pthread_detach(self.id) };
143 debug_assert_eq!(ret, 0);
144 }
145}
146
147pub fn available_parallelism() -> io::Result<NonZero<usize>> {
148 cfg_select! {
149 any(
150 target_os = "android",
151 target_os = "emscripten",
152 target_os = "fuchsia",
153 target_os = "hurd",
154 target_os = "linux",
155 target_os = "aix",
156 target_vendor = "apple",
157 target_os = "cygwin",
158 ) => {
159 #[allow(unused_assignments)]
160 #[allow(unused_mut)]
161 let mut quota = usize::MAX;
162
163 #[cfg(any(target_os = "android", target_os = "linux"))]
164 {
165 quota = cgroups::quota().max(1);
166 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
167 unsafe {
168 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
169 let count = libc::CPU_COUNT(&set) as usize;
170 let count = count.min(quota);
171
172 if let Some(count) = NonZero::new(count) {
177 return Ok(count)
178 }
179 }
180 }
181 }
182 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
183 -1 => Err(io::Error::last_os_error()),
184 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
185 cpus => {
186 let count = cpus as usize;
187 let count = count.min(quota);
189 Ok(unsafe { NonZero::new_unchecked(count) })
190 }
191 }
192 }
193 any(
194 target_os = "freebsd",
195 target_os = "dragonfly",
196 target_os = "openbsd",
197 target_os = "netbsd",
198 ) => {
199 use crate::ptr;
200
201 #[cfg(target_os = "freebsd")]
202 {
203 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
204 unsafe {
205 if libc::cpuset_getaffinity(
206 libc::CPU_LEVEL_WHICH,
207 libc::CPU_WHICH_PID,
208 -1,
209 size_of::<libc::cpuset_t>(),
210 &mut set,
211 ) == 0 {
212 let count = libc::CPU_COUNT(&set) as usize;
213 if count > 0 {
214 return Ok(NonZero::new_unchecked(count));
215 }
216 }
217 }
218 }
219
220 #[cfg(target_os = "netbsd")]
221 {
222 unsafe {
223 let set = libc::_cpuset_create();
224 if !set.is_null() {
225 let mut count: usize = 0;
226 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
227 for i in 0..libc::cpuid_t::MAX {
228 match libc::_cpuset_isset(i, set) {
229 -1 => break,
230 0 => continue,
231 _ => count = count + 1,
232 }
233 }
234 }
235 libc::_cpuset_destroy(set);
236 if let Some(count) = NonZero::new(count) {
237 return Ok(count);
238 }
239 }
240 }
241 }
242
243 let mut cpus: libc::c_uint = 0;
244 let mut cpus_size = size_of_val(&cpus);
245
246 unsafe {
247 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
248 }
249
250 if cpus < 1 {
252 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
253 let res = unsafe {
254 libc::sysctl(
255 mib.as_mut_ptr(),
256 2,
257 (&raw mut cpus) as *mut _,
258 (&raw mut cpus_size) as *mut _,
259 ptr::null_mut(),
260 0,
261 )
262 };
263
264 if res == -1 {
266 return Err(io::Error::last_os_error());
267 } else if cpus == 0 {
268 return Err(io::Error::UNKNOWN_THREAD_COUNT);
269 }
270 }
271
272 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
273 }
274 target_os = "nto" => {
275 unsafe {
276 use libc::_syspage_ptr;
277 if _syspage_ptr.is_null() {
278 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
279 } else {
280 let cpus = (*_syspage_ptr).num_cpu;
281 NonZero::new(cpus as usize)
282 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
283 }
284 }
285 }
286 any(target_os = "solaris", target_os = "illumos") => {
287 let mut cpus = 0u32;
288 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
289 return Err(io::Error::UNKNOWN_THREAD_COUNT);
290 }
291 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
292 }
293 target_os = "haiku" => {
294 unsafe {
297 let mut sinfo: libc::system_info = crate::mem::zeroed();
298 let res = libc::get_system_info(&mut sinfo);
299
300 if res != libc::B_OK {
301 return Err(io::Error::UNKNOWN_THREAD_COUNT);
302 }
303
304 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
305 }
306 }
307 target_os = "vxworks" => {
308 unsafe{
313 let set = libc::vxCpuEnabledGet();
314 Ok(NonZero::new_unchecked(set.count_ones() as usize))
315 }
316 }
317 _ => {
318 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
320 }
321 }
322}
323
324pub fn current_os_id() -> Option<u64> {
325 cfg_select! {
331 any(target_os = "android", target_os = "linux") => {
333 use crate::sys::pal::weak::syscall;
334
335 syscall!(fn gettid() -> libc::pid_t;);
338
339 let id: libc::pid_t = unsafe { gettid() };
341 Some(id as u64)
342 }
343 target_os = "nto" => {
344 let id: libc::pid_t = unsafe { libc::gettid() };
346 Some(id as u64)
347 }
348 target_os = "openbsd" => {
349 let id: libc::pid_t = unsafe { libc::getthrid() };
351 Some(id as u64)
352 }
353 target_os = "freebsd" => {
354 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
356 Some(id as u64)
357 }
358 target_os = "netbsd" => {
359 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
361 Some(id as u64)
362 }
363 any(target_os = "illumos", target_os = "solaris") => {
364 let id: libc::pthread_t = unsafe { libc::pthread_self() };
367 Some(id as u64)
368 }
369 target_vendor = "apple" => {
370 let mut id = 0u64;
372 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
374 if status == 0 {
375 Some(id)
376 } else {
377 None
378 }
379 }
380 _ => None,
382 }
383}
384
385#[cfg(any(
386 target_os = "linux",
387 target_os = "nto",
388 target_os = "solaris",
389 target_os = "illumos",
390 target_os = "vxworks",
391 target_os = "cygwin",
392 target_vendor = "apple",
393))]
394fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
395 let mut result = [0; MAX_WITH_NUL];
396 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
397 *dst = *src as libc::c_char;
398 }
399 result
400}
401
402#[cfg(target_os = "android")]
403pub fn set_name(name: &CStr) {
404 const PR_SET_NAME: libc::c_int = 15;
405 unsafe {
406 let res = libc::prctl(
407 PR_SET_NAME,
408 name.as_ptr(),
409 0 as libc::c_ulong,
410 0 as libc::c_ulong,
411 0 as libc::c_ulong,
412 );
413 debug_assert_eq!(res, 0);
415 }
416}
417
418#[cfg(any(
419 target_os = "linux",
420 target_os = "freebsd",
421 target_os = "dragonfly",
422 target_os = "nuttx",
423 target_os = "cygwin"
424))]
425pub fn set_name(name: &CStr) {
426 unsafe {
427 cfg_select! {
428 any(target_os = "linux", target_os = "cygwin") => {
429 const TASK_COMM_LEN: usize = 16;
431 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
432 }
433 _ => {
434 }
436 };
437 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
440 debug_assert_eq!(res, 0);
442 }
443}
444
445#[cfg(target_os = "openbsd")]
446pub fn set_name(name: &CStr) {
447 unsafe {
448 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
449 }
450}
451
452#[cfg(target_vendor = "apple")]
453pub fn set_name(name: &CStr) {
454 unsafe {
455 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
456 let res = libc::pthread_setname_np(name.as_ptr());
457 debug_assert_eq!(res, 0);
459 }
460}
461
462#[cfg(target_os = "netbsd")]
463pub fn set_name(name: &CStr) {
464 unsafe {
465 let res = libc::pthread_setname_np(
466 libc::pthread_self(),
467 c"%s".as_ptr(),
468 name.as_ptr() as *mut libc::c_void,
469 );
470 debug_assert_eq!(res, 0);
471 }
472}
473
474#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
475pub fn set_name(name: &CStr) {
476 weak!(
477 fn pthread_setname_np(thread: libc::pthread_t, name: *const libc::c_char) -> libc::c_int;
478 );
479
480 if let Some(f) = pthread_setname_np.get() {
481 #[cfg(target_os = "nto")]
482 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
483 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
484 const THREAD_NAME_MAX: usize = 32;
485
486 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
487 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
488 debug_assert_eq!(res, 0);
489 }
490}
491
492#[cfg(target_os = "fuchsia")]
493pub fn set_name(name: &CStr) {
494 use crate::sys::pal::fuchsia::*;
495 unsafe {
496 zx_object_set_property(
497 zx_thread_self(),
498 ZX_PROP_NAME,
499 name.as_ptr() as *const libc::c_void,
500 name.to_bytes().len(),
501 );
502 }
503}
504
505#[cfg(target_os = "haiku")]
506pub fn set_name(name: &CStr) {
507 unsafe {
508 let thread_self = libc::find_thread(ptr::null_mut());
509 let res = libc::rename_thread(thread_self, name.as_ptr());
510 debug_assert_eq!(res, libc::B_OK);
512 }
513}
514
515#[cfg(target_os = "vxworks")]
516pub fn set_name(name: &CStr) {
517 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
518 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
519 debug_assert_eq!(res, libc::OK);
520}
521
522#[cfg(not(target_os = "espidf"))]
523pub fn sleep(dur: Duration) {
524 let mut secs = dur.as_secs();
525 let mut nsecs = dur.subsec_nanos() as _;
526
527 unsafe {
530 while secs > 0 || nsecs > 0 {
531 let mut ts = libc::timespec {
532 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
533 tv_nsec: nsecs,
534 };
535 secs -= ts.tv_sec as u64;
536 let ts_ptr = &raw mut ts;
537 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
538 assert_eq!(os::errno(), libc::EINTR);
539 secs += ts.tv_sec as u64;
540 nsecs = ts.tv_nsec;
541 } else {
542 nsecs = 0;
543 }
544 }
545 }
546}
547
548#[cfg(target_os = "espidf")]
549pub fn sleep(dur: Duration) {
550 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
560
561 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
568
569 while micros > 0 {
570 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
571 unsafe {
572 libc::usleep(st);
573 }
574
575 micros -= st as u128;
576 }
577}
578
579#[cfg(any(
582 target_os = "freebsd",
583 target_os = "netbsd",
584 target_os = "linux",
585 target_os = "android",
586 target_os = "solaris",
587 target_os = "illumos",
588 target_os = "dragonfly",
589 target_os = "hurd",
590 target_os = "fuchsia",
591 target_os = "vxworks",
592))]
593pub fn sleep_until(deadline: crate::time::Instant) {
594 use crate::time::Instant;
595
596 let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
597 let now = Instant::now();
601 if let Some(delay) = deadline.checked_duration_since(now) {
602 sleep(delay);
603 }
604 return;
605 };
606
607 unsafe {
608 loop {
610 let res = libc::clock_nanosleep(
611 crate::sys::time::Instant::CLOCK_ID,
612 libc::TIMER_ABSTIME,
613 &ts,
614 core::ptr::null_mut(), );
616
617 if res == 0 {
618 break;
619 } else {
620 assert_eq!(
621 res,
622 libc::EINTR,
623 "timespec is in range,
624 clockid is valid and kernel should support it"
625 );
626 }
627 }
628 }
629}
630
631pub fn yield_now() {
632 let ret = unsafe { libc::sched_yield() };
633 debug_assert_eq!(ret, 0);
634}
635
636#[cfg(any(target_os = "android", target_os = "linux"))]
637mod cgroups {
638 use crate::borrow::Cow;
644 use crate::ffi::OsString;
645 use crate::fs::{File, exists};
646 use crate::io::{BufRead, Read};
647 use crate::os::unix::ffi::OsStringExt;
648 use crate::path::{Path, PathBuf};
649 use crate::str::from_utf8;
650
651 #[derive(PartialEq)]
652 enum Cgroup {
653 V1,
654 V2,
655 }
656
657 pub(super) fn quota() -> usize {
660 let mut quota = usize::MAX;
661 if cfg!(miri) {
662 return quota;
665 }
666
667 let _: Option<()> = try {
668 let mut buf = Vec::with_capacity(128);
669 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
671 let (cgroup_path, version) =
672 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
673 let mut fields = line.splitn(3, |&c| c == b':');
674 let version = match fields.nth(1) {
676 Some(b"") => Cgroup::V2,
677 Some(controllers)
678 if from_utf8(controllers)
679 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
680 {
681 Cgroup::V1
682 }
683 _ => return previous,
684 };
685
686 if previous.is_some() && version == Cgroup::V2 {
688 return previous;
689 }
690
691 let path = fields.last()?;
692 Some((path[1..].to_owned(), version))
694 })?;
695 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
696
697 quota = match version {
698 Cgroup::V1 => quota_v1(cgroup_path),
699 Cgroup::V2 => quota_v2(cgroup_path),
700 };
701 };
702
703 quota
704 }
705
706 fn quota_v2(group_path: PathBuf) -> usize {
707 let mut quota = usize::MAX;
708
709 let mut path = PathBuf::with_capacity(128);
710 let mut read_buf = String::with_capacity(20);
711
712 let cgroup_mount = "/sys/fs/cgroup";
714
715 path.push(cgroup_mount);
716 path.push(&group_path);
717
718 path.push("cgroup.controllers");
719
720 if matches!(exists(&path), Err(_) | Ok(false)) {
722 return usize::MAX;
723 };
724
725 path.pop();
726
727 let _: Option<()> = try {
728 while path.starts_with(cgroup_mount) {
729 path.push("cpu.max");
730
731 read_buf.clear();
732
733 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
734 let raw_quota = read_buf.lines().next()?;
735 let mut raw_quota = raw_quota.split(' ');
736 let limit = raw_quota.next()?;
737 let period = raw_quota.next()?;
738 match (limit.parse::<usize>(), period.parse::<usize>()) {
739 (Ok(limit), Ok(period)) if period > 0 => {
740 quota = quota.min(limit / period);
741 }
742 _ => {}
743 }
744 }
745
746 path.pop(); path.pop(); }
749 };
750
751 quota
752 }
753
754 fn quota_v1(group_path: PathBuf) -> usize {
755 let mut quota = usize::MAX;
756 let mut path = PathBuf::with_capacity(128);
757 let mut read_buf = String::with_capacity(20);
758
759 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
762 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
763 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
764 find_mountpoint,
768 ];
769
770 for mount in mounts {
771 let Some((mount, group_path)) = mount(&group_path) else { continue };
772
773 path.clear();
774 path.push(mount.as_ref());
775 path.push(&group_path);
776
777 if matches!(exists(&path), Err(_) | Ok(false)) {
779 continue;
780 }
781
782 while path.starts_with(mount.as_ref()) {
783 let mut parse_file = |name| {
784 path.push(name);
785 read_buf.clear();
786
787 let f = File::open(&path);
788 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
790 let parsed = read_buf.trim().parse::<usize>().ok()?;
791
792 Some(parsed)
793 };
794
795 let limit = parse_file("cpu.cfs_quota_us");
796 let period = parse_file("cpu.cfs_period_us");
797
798 match (limit, period) {
799 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
800 _ => {}
801 }
802
803 path.pop();
804 }
805
806 break;
809 }
810
811 quota
812 }
813
814 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
819 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
820 let mut line = String::with_capacity(256);
821 loop {
822 line.clear();
823 if reader.read_line(&mut line).ok()? == 0 {
824 break;
825 }
826
827 let line = line.trim();
828 let mut items = line.split(' ');
829
830 let sub_path = items.nth(3)?;
831 let mount_point = items.next()?;
832 let mount_opts = items.next_back()?;
833 let filesystem_type = items.nth_back(1)?;
834
835 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
836 continue;
838 }
839
840 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
841
842 if !group_path.starts_with(sub_path) {
843 continue;
846 }
847
848 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
849
850 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
851 }
852
853 None
854 }
855}
856
857#[cfg(all(target_os = "linux", target_env = "gnu"))]
863unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
864 dlsym!(
868 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
869 );
870
871 match __pthread_get_minstack.get() {
872 None => libc::PTHREAD_STACK_MIN,
873 Some(f) => unsafe { f(attr) },
874 }
875}
876
877#[cfg(all(
879 not(all(target_os = "linux", target_env = "gnu")),
880 not(any(target_os = "netbsd", target_os = "nuttx"))
881))]
882unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
883 libc::PTHREAD_STACK_MIN
884}
885
886#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
887unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
888 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
889
890 *STACK.get_or_init(|| {
891 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
892 if stack < 0 {
893 stack = 2048; }
895
896 stack as usize
897 })
898}