MonsterAI .Lab

Flutter • Rust • Next.js

返回首页
Rust

Rust 并发篇 (二十):共享状态并发——Arc 与 Mutex 组合拳实战

Waitwalker2026-08-2913 min
## 1. Arc<Mutex<T>> 黄金拍档 在多线程中修改计数器: ```rust use std::sync::{Arc, Mutex}; use std::thread; fn main() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter_clone = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter_clone.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("最终计数值: {}", *counter.lock().unwrap()); } ```
#Rust#并发#Mutex#Arc#高性能
回到文章列表 →