5.3 示例
03-示例 — Comprehensive Rust
1分钟内可阅读完
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/concurrency/shared-state/example.html
5.3 示例
来看 Arc 与 Mutex 的实际用法:
| |
可行解法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19// Copyright 2024 Google LLC // SPDX-License-Identifier: Apache-2.0 use std::sync::{Arc, Mutex}; use std::thread; fn main() { let v = Arc::new(Mutex::new(vec![10, 20, 30])); let mut handles = Vec::new(); for i in 0..5 { let v = Arc::clone(&v); handles.push(thread::spawn(move || { let mut v = v.lock().unwrap(); v.push(10 * i); println!("v: {v:?}"); })); } handles.into_iter().for_each(|h| h.join().unwrap()); }要点:
v同时包在Arc与Mutex中,因为它们关注的问题是正交的。
- 把
Mutex包在Arc里是在线程间共享可变状态的常见模式。v: Arc<_>需要克隆,以便为每个新派生的线程提供新引用。注意 lambda 签名中加了move。- 引入代码块以尽可能缩小
LockGuard的作用域。