Rust 的 Arc<Mutex<T>> 的用法示例源代码

在 Rust 中,Arc<Mutex<T>> 是一种组合类型,它结合了 Arc(原子引用计数)和 Mutex(互斥锁)。Arc 用于在多个所有者之间共享数据,而 Mutex 用于确保在任意时刻只有一个线程可以访问被保护的数据。这种组合类型在并发编程中非常有用,特别是当你需要在多个线程之间安全地共享和修改数据时。

下面是一个使用 Arc<Mutex<T>> 的简单示例,它演示了如何在多线程环境中安全地共享和修改一个整数值:

rust 复制代码
use std::sync::{Arc, Mutex};
use std::thread;
use std::random;

fn main() {
    // 创建一个 Arc<Mutex<i32>>,初始值为 0
    let counter = Arc::new(Mutex::new(0));

    // 创建多个线程,每个线程都会增加计数器的值
    let mut threads = Vec::new();
    for _ in 0..10 {
        let counter = counter.clone();
        let thread = thread::spawn(move || {
            // 获取互斥锁,以便安全地访问和修改计数器的值
            let mut num = counter.lock().unwrap();
            // 随机增加计数器的值
            *num += random::thread_rng().gen_range(1..=10);
        });
        threads.push(thread);
    }

    // 等待所有线程完成
    for thread in threads {
        thread.join().unwrap();
    }

    // 打印最终的计数器值
    let final_count = counter.lock().unwrap();
    println!("Final counter value: {}", *final_count);
}

在这个示例中,我们首先创建了一个 Arc<Mutex<i32>>,其中包含一个初始值为 0 的 i32 类型的计数器。然后,我们创建了 10 个线程,每个线程都会获取互斥锁,以便安全地访问和修改计数器的值。每个线程都会随机增加计数器的值。最后,我们等待所有线程完成,并打印最终的计数器值。

请注意,我们在每个线程中使用 counter.clone() 来获取 Arc<Mutex<i32>> 的一个克隆。这是因为 Arc 允许我们创建多个指向同一数据的引用,而 Mutex 则确保在任意时刻只有一个线程可以访问被保护的数据。这种组合使得 Arc<Mutex<T>> 成为 Rust 中处理并发共享数据的一种强大工具。

相关推荐
DongLi011 天前
rustlings 学习笔记 -- exercises/05_vecs
rust
番茄灭世神2 天前
Rust学习笔记第2篇
rust·编程语言
shimly1234562 天前
(done) 速通 rustlings(20) 错误处理1 --- 不涉及Traits
rust
shimly1234562 天前
(done) 速通 rustlings(19) Option
rust
@atweiwei2 天前
rust所有权机制详解
开发语言·数据结构·后端·rust·内存·所有权
shimly1234562 天前
(done) 速通 rustlings(24) 错误处理2 --- 涉及Traits
rust
shimly1234562 天前
(done) 速通 rustlings(23) 特性 Traits
rust
shimly1234562 天前
(done) 速通 rustlings(17) 哈希表
rust
shimly1234562 天前
(done) 速通 rustlings(15) 字符串
rust
shimly1234562 天前
(done) 速通 rustlings(22) 泛型
rust