mod common;
use oscall::{ErrorKind, thread};
#[cfg_attr(target_family = "wasm", allow(dead_code))]
fn on_new_thread<T: Send>(f: impl FnOnce() -> T + Send) -> T {
if cfg!(target_os = "wasi") {
f()
} else {
std::thread::scope(|s| s.spawn(f).join().unwrap())
}
}
#[test]
fn id() {
let mine = thread::id();
assert_ne!(mine, 0);
assert_eq!(thread::id(), mine);
if cfg!(target_family = "wasm") {
assert_eq!(mine, 1);
return; }
let barrier = std::sync::Barrier::new(4);
let mut ids = std::thread::scope(|s| {
let threads: Vec<_> = (0..4)
.map(|_| {
s.spawn(|| {
let id = thread::id();
barrier.wait();
assert_eq!(thread::id(), id);
id
})
})
.collect();
threads
.into_iter()
.map(|t| t.join().unwrap())
.collect::<Vec<_>>()
});
ids.push(mine);
assert!(ids.iter().all(|&id| id != 0));
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), 5);
}
#[cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86")))]
#[test]
fn id_is_the_systems() {
on_new_thread(|| {
let id = thread::id();
assert_ne!(id, u64::from(std::process::id()), "not the first thread");
let task = format!("/proc/self/task/{id}/comm");
if std::path::Path::new("/proc/self/task").exists() {
assert!(std::path::Path::new(&task).exists(), "{task}");
}
});
}
#[test]
fn yield_now() {
for _ in 0..1000 {
thread::yield_now();
}
}
#[test]
fn available_parallelism() {
let count = thread::available_parallelism().unwrap();
assert!(count >= 1);
if cfg!(target_family = "wasm") {
assert_eq!(count, 1);
}
if let Ok(std_count) = std::thread::available_parallelism() {
assert!(count >= std_count.get(), "{count} < {std_count}");
if cfg!(target_os = "macos") {
assert_eq!(count, std_count.get());
}
}
}
#[cfg(not(target_family = "wasm"))]
#[test]
fn name() {
on_new_thread(|| {
let mut buf = [0u8; 256];
thread::set_name("oscall-worker").unwrap();
assert_eq!(thread::name(&mut buf).unwrap(), "oscall-worker");
thread::set_name("é").unwrap();
assert_eq!(thread::name(&mut buf).unwrap(), "é");
thread::set_name("").unwrap();
assert_eq!(thread::name(&mut buf).unwrap(), "");
thread::set_name("exact").unwrap();
assert_eq!(thread::name(&mut buf[..5]).unwrap(), "exact");
assert_eq!(
thread::name(&mut buf[..4]).unwrap_err(),
ErrorKind::BufferTooSmall
);
assert_eq!(
thread::name(&mut []).unwrap_err(),
ErrorKind::BufferTooSmall
);
assert_eq!(
thread::set_name("a\0b").unwrap_err(),
ErrorKind::InvalidInput
);
assert_eq!(thread::name(&mut buf).unwrap(), "exact");
});
}
#[cfg(not(target_family = "wasm"))]
#[test]
fn name_is_cut_at_the_limit() {
let limit = if cfg!(windows) {
255
} else if cfg!(target_os = "macos") {
63
} else {
15
};
on_new_thread(|| {
let mut buf = [0u8; 256];
let long = "é".repeat(200);
thread::set_name(&long).unwrap();
let name = thread::name(&mut buf).unwrap();
assert_eq!(name, "é".repeat(limit / 2));
let exact = "x".repeat(limit);
thread::set_name(&exact).unwrap();
assert_eq!(thread::name(&mut buf).unwrap(), exact);
let over = "x".repeat(limit + 1);
thread::set_name(&over).unwrap();
assert_eq!(thread::name(&mut buf).unwrap(), exact);
});
}
#[cfg(any(target_os = "linux", target_os = "macos", windows))]
#[test]
fn name_matches_std() {
std::thread::Builder::new()
.name("oscall-by-std".into())
.spawn(|| {
let mut buf = [0u8; 64];
assert_eq!(thread::name(&mut buf).unwrap(), "oscall-by-std");
})
.unwrap()
.join()
.unwrap();
}
#[cfg(target_family = "wasm")]
#[test]
fn name_is_unsupported() {
let mut buf = [0u8; 64];
assert_eq!(
thread::set_name("name").unwrap_err(),
ErrorKind::Unsupported
);
assert_eq!(thread::name(&mut buf).unwrap_err(), ErrorKind::Unsupported);
}
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_affinity() {
use oscall::thread::linux;
const WORDS: usize = 8192 / usize::BITS as usize;
on_new_thread(|| {
let mut mask = [usize::MAX; WORDS];
linux::affinity(&mut mask).unwrap();
let count: usize = mask.iter().map(|w| w.count_ones() as usize).sum();
assert_eq!(count, thread::available_parallelism().unwrap());
assert_eq!(
linux::set_affinity(&[0; WORDS]).unwrap_err(),
ErrorKind::InvalidInput
);
assert_eq!(
linux::set_affinity(&[]).unwrap_err(),
ErrorKind::InvalidInput
);
let word = mask.iter().rposition(|&w| w != 0).unwrap();
let bit = usize::BITS - 1 - mask[word].leading_zeros();
let mut one = [0usize; WORDS];
one[word] = 1 << bit;
linux::set_affinity(&one[..=word]).unwrap();
let mut now = [usize::MAX; WORDS];
linux::affinity(&mut now).unwrap();
assert_eq!(now, one);
assert_eq!(thread::available_parallelism().unwrap(), 1);
let inherited = std::thread::scope(|s| {
s.spawn(|| {
let mut mask = [0usize; WORDS];
linux::affinity(&mut mask).unwrap();
mask
})
.join()
.unwrap()
});
assert_eq!(inherited, one);
linux::set_affinity(&mask).unwrap();
linux::affinity(&mut now).unwrap();
assert_eq!(now, mask);
});
}
#[cfg(windows)]
#[test]
fn windows_affinity() {
use oscall::thread::windows;
on_new_thread(|| {
let mask = windows::affinity().unwrap();
assert_ne!(mask, 0);
assert!(mask.count_ones() as usize <= thread::available_parallelism().unwrap());
assert_eq!(
windows::set_affinity(0).unwrap_err(),
ErrorKind::InvalidInput
);
let one = 1 << (usize::BITS - 1 - mask.leading_zeros());
windows::set_affinity(one).unwrap();
assert_eq!(windows::affinity().unwrap(), one);
windows::set_affinity(mask).unwrap();
assert_eq!(windows::affinity().unwrap(), mask);
});
}
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_nice() {
let before = thread::linux::nice().unwrap();
assert!((-20..=19).contains(&before), "{before}");
if before < 19 {
on_new_thread(|| {
assert_eq!(thread::linux::nice().unwrap(), before);
thread::linux::set_nice(before + 1).unwrap();
assert_eq!(thread::linux::nice().unwrap(), before + 1);
assert_eq!(on_new_thread(thread::linux::nice).unwrap(), before + 1);
match thread::linux::set_nice(before) {
Ok(()) => assert_eq!(thread::linux::nice().unwrap(), before),
Err(error) => assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error}"),
}
thread::linux::set_nice(100).unwrap();
assert_eq!(thread::linux::nice().unwrap(), 19);
});
}
assert_eq!(thread::linux::nice().unwrap(), before);
}
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod linux_raw {
use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use core::time::Duration;
use oscall::thread::linux::spawn_raw;
use oscall::{sync, thread, time};
struct Report {
id: AtomicU32,
sum: [AtomicU32; 2],
text: AtomicUsize,
done: AtomicU32,
release: AtomicU32,
}
impl Report {
const fn new() -> Self {
Self {
id: AtomicU32::new(0),
sum: [AtomicU32::new(0), AtomicU32::new(0)],
text: AtomicUsize::new(0),
done: AtomicU32::new(0),
release: AtomicU32::new(0),
}
}
}
fn deep(depth: u32, seed: u64) -> u64 {
let mut frame = [0u64; 128];
for (i, slot) in frame.iter_mut().enumerate() {
*slot = seed.wrapping_mul(i as u64 + 1);
}
let frame = core::hint::black_box(&mut frame);
if depth == 0 {
frame[127]
} else {
deep(depth - 1, seed + 1).wrapping_add(frame[depth as usize % 128])
}
}
fn deep_expected(depth: u32, seed: u64) -> u64 {
let mut total = (seed + u64::from(depth)).wrapping_mul(128);
for level in 1..=depth {
let seed = seed + u64::from(depth - level);
total = total.wrapping_add(seed.wrapping_mul(u64::from(level % 128) + 1));
}
total
}
fn work(arg: usize) {
let report = unsafe { &*(arg as *const Report) };
report.id.store(thread::id() as u32, Ordering::Release);
let mut text = Text {
buf: [0; 64],
len: 0,
};
let value = core::hint::black_box(1.5f64) * core::hint::black_box(2.25f64);
let wide = core::hint::black_box(u128::MAX / 3) / core::hint::black_box(7u128);
let _ = core::fmt::write(&mut text, format_args!("{value:.3} {wide}"));
report.text.store(
text.matches(b"3.375 16203922234330403022065457496750867212"),
Ordering::Release,
);
let sum = deep(200, 3);
report.sum[0].store(sum as u32, Ordering::Release);
report.sum[1].store((sum >> 32) as u32, Ordering::Release);
let _ = time::sleep(Duration::from_millis(1));
thread::yield_now();
report.done.store(1, Ordering::Release);
sync::wake_all(&report.done);
while report.release.load(Ordering::Acquire) == 1 {
let _ = sync::wait(&report.release, 1, Some(Duration::from_millis(50)));
}
}
struct Text {
buf: [u8; 64],
len: usize,
}
impl Text {
fn matches(&self, expected: &[u8]) -> usize {
usize::from(&self.buf[..self.len] == expected)
}
}
impl core::fmt::Write for Text {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
let end = self.len + s.len();
self.buf
.get_mut(self.len..end)
.ok_or(core::fmt::Error)?
.copy_from_slice(s.as_bytes());
self.len = end;
Ok(())
}
}
fn wait_done(report: &Report) {
let start = std::time::Instant::now();
while report.done.load(Ordering::Acquire) == 0 {
assert!(
start.elapsed() < Duration::from_secs(60),
"the thread never ran"
);
let _ = sync::wait(&report.done, 0, Some(Duration::from_millis(100)));
}
}
fn check(report: &Report, id: u32) {
assert_eq!(report.id.load(Ordering::Acquire), id);
assert_eq!(report.text.load(Ordering::Acquire), 1);
let sum = u64::from(report.sum[0].load(Ordering::Acquire))
| u64::from(report.sum[1].load(Ordering::Acquire)) << 32;
assert_eq!(sum, deep_expected(200, 3));
}
#[test]
fn join() {
static REPORT: Report = Report::new();
assert_eq!(deep(200, 3), deep_expected(200, 3));
REPORT.release.store(1, Ordering::Release);
let thread = unsafe { spawn_raw(256 * 1024, work, &raw const REPORT as usize) }.unwrap();
let id = thread.id();
assert_ne!(u64::from(id), thread::id());
assert_ne!(id, 0);
wait_done(&REPORT);
assert!(!thread.is_finished());
assert!(format!("{thread:?}").contains(&id.to_string()));
if !super::emulated() {
let task = format!("/proc/self/task/{id}");
assert!(std::path::Path::new(&task).exists(), "{task}");
}
REPORT.release.store(0, Ordering::Release);
sync::wake_all(&REPORT.release);
thread.join().unwrap();
check(&REPORT, id);
}
#[test]
fn several() {
const COUNT: usize = 16;
static REPORTS: [Report; COUNT] = [const { Report::new() }; COUNT];
let threads: Vec<_> = REPORTS
.iter()
.map(|report| {
unsafe { spawn_raw(256 * 1024, work, core::ptr::from_ref(report) as usize) }
.unwrap()
})
.collect();
let mut ids: Vec<u32> = threads.iter().map(|thread| thread.id()).collect();
for (thread, report) in threads.into_iter().zip(&REPORTS).rev() {
let id = thread.id();
thread.join().unwrap();
check(report, id);
}
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), COUNT);
}
#[test]
fn detached() {
const ROUNDS: usize = 64;
const STACK: usize = 8 << 20;
static REPORT: Report = Report::new();
for round in 0..ROUNDS {
REPORT.done.store(0, Ordering::Release);
let thread = unsafe { spawn_raw(STACK, work, &raw const REPORT as usize) }.unwrap();
let id = thread.id();
if round % 2 == 0 {
drop(thread);
wait_done(&REPORT);
} else {
wait_done(&REPORT);
thread.detach();
}
check(&REPORT, id);
}
if !super::emulated() {
let start = std::time::Instant::now();
loop {
let stacks = std::fs::read_to_string("/proc/self/maps")
.unwrap()
.lines()
.filter(|line| {
let range = line.split(' ').next().unwrap();
let (low, high) = range.split_once('-').unwrap();
let low = usize::from_str_radix(low, 16).unwrap();
let high = usize::from_str_radix(high, 16).unwrap();
(STACK..STACK + (1 << 20)).contains(&(high - low))
&& line.contains(" rw-p ")
})
.count();
if stacks < ROUNDS / 4 {
break;
}
assert!(
start.elapsed() < Duration::from_secs(30),
"{stacks} stacks are still mapped"
);
std::thread::sleep(Duration::from_millis(20));
}
}
}
#[test]
fn errors() {
fn nothing(_: usize) {}
let error = unsafe { spawn_raw(usize::MAX, nothing, 0) }.unwrap_err();
assert_eq!(error.kind(), oscall::ErrorKind::InvalidInput, "{error}");
let error = unsafe { spawn_raw(usize::MAX - (64 << 20), nothing, 0) }.unwrap_err();
assert_eq!(error.kind(), oscall::ErrorKind::OutOfMemory, "{error}");
unsafe { spawn_raw(0, nothing, 0) }.unwrap().join().unwrap();
}
}
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
fn emulated() -> bool {
common::emulated()
}
#[cfg(any(target_os = "macos", windows))]
mod spawned {
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
#[cfg(target_os = "macos")]
use oscall::thread::macos as system;
#[cfg(windows)]
use oscall::thread::windows as system;
use oscall::{ErrorKind, thread};
#[test]
fn spawn_fn() {
static SEEN: AtomicUsize = AtomicUsize::new(0);
static ID: AtomicU64 = AtomicU64::new(0);
fn work(arg: usize) {
ID.store(thread::id(), Ordering::Release);
thread_local!(static LOCAL: std::cell::Cell<usize> = const { std::cell::Cell::new(1) });
LOCAL.set(LOCAL.get() + arg);
let text = format!("{}", LOCAL.get());
let _ = std::thread::current().id();
SEEN.store(text.parse().unwrap(), Ordering::Release);
}
let handle = system::spawn_fn(work, 41).unwrap();
let id = handle.id();
assert_ne!(id, 0);
assert_ne!(id, thread::id());
assert!(format!("{handle:?}").contains("Thread"));
handle.join().unwrap();
assert_eq!(SEEN.load(Ordering::Acquire), 42);
assert_eq!(ID.load(Ordering::Acquire), id);
}
#[test]
fn builder() {
static NAME_OK: AtomicUsize = AtomicUsize::new(0);
static STACK: AtomicUsize = AtomicUsize::new(0);
fn work(_: usize) {
let mut buf = [0u8; 64];
let name = thread::name(&mut buf).unwrap();
NAME_OK.store(usize::from(name == "oscall worker"), Ordering::Release);
let bounds = system::stack_bounds();
STACK.store(bounds.end - bounds.start, Ordering::Release);
}
let handle = system::Builder::new()
.name("oscall worker")
.stack_size(3 << 20)
.spawn_fn(work, 0)
.unwrap();
handle.join().unwrap();
assert_eq!(NAME_OK.load(Ordering::Acquire), 1);
let stack = STACK.load(Ordering::Acquire);
assert!((3 << 20..4 << 20).contains(&stack), "{stack}");
for (asked, range) in [(0, 2 << 20..3 << 20), (64 << 10, 64 << 10..256 << 10)] {
STACK.store(0, Ordering::Release);
let handle = system::Builder::new()
.stack_size(asked)
.spawn_fn(work, 0)
.unwrap();
handle.join().unwrap();
let stack = STACK.load(Ordering::Acquire);
assert!(range.contains(&stack), "{asked}: {stack}");
}
let error = system::Builder::new()
.name("a\0b")
.spawn_fn(work, 0)
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput);
let _ = format!("{:?}", system::Builder::default().clone());
}
#[cfg(feature = "alloc")]
#[test]
fn spawn() {
let numbers: Vec<u64> = (1..=3).collect();
let handle = system::spawn(move || {
let sum: u64 = numbers.iter().sum();
(sum, thread::id(), String::from("done"))
})
.unwrap();
let id = handle.id();
assert!(format!("{handle:?}").contains("JoinHandle"));
let (sum, seen, text) = handle.join().unwrap();
assert_eq!((sum, text.as_str()), (6, "done"));
assert_eq!(seen, id);
let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
let handles: Vec<_> = (0..8u64)
.map(|i| {
let barrier = barrier.clone();
system::Builder::new()
.name("oscall many")
.spawn(move || {
barrier.wait();
i * i
})
.unwrap()
})
.collect();
let squares: Vec<u64> = handles.into_iter().map(|h| h.join().unwrap()).collect();
assert_eq!(squares, [0, 1, 4, 9, 16, 25, 36, 49]);
let error = system::Builder::new().name("a\0").spawn(|| ()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput);
}
#[cfg(feature = "alloc")]
#[test]
fn detached() {
use std::sync::mpsc;
use std::time::Duration;
struct Tell(mpsc::Sender<&'static str>);
impl Drop for Tell {
fn drop(&mut self) {
let _ = self.0.send("dropped");
}
}
let (sender, receiver) = mpsc::channel();
let (go, wait) = mpsc::channel::<()>();
let tell = Tell(sender.clone());
let handle = system::spawn(move || {
wait.recv().unwrap();
sender.send("ran").unwrap();
tell
})
.unwrap();
drop(handle);
go.send(()).unwrap();
let timeout = Duration::from_secs(60);
assert_eq!(receiver.recv_timeout(timeout), Ok("ran"));
assert_eq!(receiver.recv_timeout(timeout), Ok("dropped"));
let (sender, receiver) = mpsc::channel();
system::spawn(move || sender.send(7).unwrap())
.unwrap()
.detach();
assert_eq!(receiver.recv_timeout(timeout), Ok(7));
static RAN: AtomicUsize = AtomicUsize::new(0);
system::spawn_fn(|value| RAN.store(value, Ordering::Release), 9)
.unwrap()
.detach();
let start = std::time::Instant::now();
while RAN.load(Ordering::Acquire) != 9 {
assert!(start.elapsed() < timeout);
std::thread::sleep(Duration::from_millis(1));
}
}
#[test]
fn stack_bounds() {
let check = || {
let local = 0u8;
let address = &raw const local as usize;
let bounds = system::stack_bounds();
assert!(bounds.contains(&address), "{address:#x} in {bounds:#x?}");
bounds.end - bounds.start
};
let size = check();
assert!(size >= 64 << 10, "{size}");
let size = std::thread::Builder::new()
.stack_size(5 << 20)
.spawn(check)
.unwrap()
.join()
.unwrap();
assert!((5 << 20..6 << 20).contains(&size), "{size}");
}
#[cfg(windows)]
#[test]
fn windows_priority() {
super::on_new_thread(|| {
assert_eq!(system::priority().unwrap(), 0);
for priority in [1, -1, 2, -2, -15, 15, 0] {
system::set_priority(priority).unwrap();
assert_eq!(system::priority().unwrap(), priority);
}
let error = system::set_priority(7).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error}");
assert_eq!(system::priority().unwrap(), 0);
});
assert_eq!(system::priority().unwrap(), 0);
}
#[cfg(target_os = "macos")]
#[test]
fn macos_qos() {
use system::Qos;
for class in [
Qos::Utility,
Qos::Background,
Qos::Default,
Qos::UserInitiated,
Qos::UserInteractive,
] {
super::on_new_thread(move || {
system::set_qos(class).unwrap();
assert_eq!(system::qos(), Some(class));
});
}
#[cfg(feature = "alloc")]
{
let class = system::spawn(|| {
system::set_qos(Qos::Utility).unwrap();
system::qos()
});
assert_eq!(class.unwrap().join().unwrap(), Some(Qos::Utility));
}
}
}