rust/tests/run-pass/sync_singlethread.rs
2020-05-04 09:45:15 +02:00

66 lines
1.4 KiB
Rust

#![feature(rustc_private, renamed_spin_loop)]
use std::sync::{Mutex, TryLockError};
use std::sync::atomic;
use std::hint;
fn main() {
test_mutex_stdlib();
#[cfg(not(target_os = "windows"))] // TODO: implement RwLock on Windows
{
test_rwlock_stdlib();
}
test_spin_loop_hint();
test_thread_yield_now();
}
fn test_mutex_stdlib() {
let m = Mutex::new(0);
{
let _guard = m.lock();
assert!(m.try_lock().unwrap_err().would_block());
}
drop(m.try_lock().unwrap());
drop(m);
}
#[cfg(not(target_os = "windows"))]
fn test_rwlock_stdlib() {
use std::sync::RwLock;
let rw = RwLock::new(0);
{
let _read_guard = rw.read().unwrap();
drop(rw.read().unwrap());
drop(rw.try_read().unwrap());
assert!(rw.try_write().unwrap_err().would_block());
}
{
let _write_guard = rw.write().unwrap();
assert!(rw.try_read().unwrap_err().would_block());
assert!(rw.try_write().unwrap_err().would_block());
}
}
trait TryLockErrorExt<T> {
fn would_block(&self) -> bool;
}
impl<T> TryLockErrorExt<T> for TryLockError<T> {
fn would_block(&self) -> bool {
match self {
TryLockError::WouldBlock => true,
TryLockError::Poisoned(_) => false,
}
}
}
fn test_spin_loop_hint() {
atomic::spin_loop_hint();
hint::spin_loop();
}
fn test_thread_yield_now() {
std::thread::yield_now();
}