diff --git a/rust/sleep_lock.rs b/rust/sleep_lock.rs new file mode 100644 index 0000000000000000000000000000000000000000..495e3f14678c4352d0644388a1c6c5a1b8027d27 --- /dev/null +++ b/rust/sleep_lock.rs @@ -0,0 +1,15 @@ +/// 用睡眠当锁(假锁) +fn main() { + fn acquire_lock(path: &str) { + while std::path::Path::new(path).exists() { + std::thread::sleep(std::time::Duration::from_millis(200)); + } + std::fs::write(path, b"locked").ok(); + } + fn release_lock(path: &str) { let _ = std::fs::remove_file(path); } + + let lock = "/tmp/lock.file"; + acquire_lock(lock); + println!("临界区..."); + release_lock(lock); +} \ No newline at end of file diff --git a/rust/timer.rs b/rust/timer.rs new file mode 100644 index 0000000000000000000000000000000000000000..8b5811a97f6e2348a9c4df35a4f719e2e01815f4 --- /dev/null +++ b/rust/timer.rs @@ -0,0 +1,9 @@ +/// 自旋“计时器”(CPU 风扇起飞)直接占满一个核心,不释放,🤣 +fn spin(ms: u64) { + let start = std::time::Instant::now(); + while start.elapsed().as_millis() < ms as u128 {} +} +fn main() { + spin(1000); + println!("OK"); +} \ No newline at end of file diff --git a/rust/unwrap.rs b/rust/unwrap.rs new file mode 100644 index 0000000000000000000000000000000000000000..b8198776af22a92499fd3aaca70c8ec0b04baba7 --- /dev/null +++ b/rust/unwrap.rs @@ -0,0 +1,6 @@ +/// 一步错步步错 +fn main() { + let port: u16 = std::env::var("PORT").unwrap().parse().unwrap(); + let cfg = std::fs::read_to_string("config.toml").unwrap(); + println!("PORT={port}, first={}", cfg.lines().next().unwrap()); +} \ No newline at end of file