【rust】Arc用法

Arc用法

Rust 中的 Arc<T> 是一个非常重要的智能指针,主要用于多个所有者共享同一份数据,尤其适合多线程场景。

Arc 全称是 Atomically Reference Counted(原子引用计数)。

如果你熟悉 Linux 内核的引用计数机制,可以把 Arc<T> 理解为:通过原子引用计数管理对象生命周期的智能指针,类似 Linux 内核中的 refcount_t 加上自动释放对象的机制。

use std::sync::Arc;

fn main() {
    let a = Arc::new(String::from("hello"));

    let b = Arc::clone(&a);
    let c = Arc::clone(&a);

    println!("{}", a);
    println!("{}", b);
    println!("{}", c);

    println!("count = {}", Arc::strong_count(&a));
}

输出:

hello
hello
hello
count = 3

下载

 

2. Arc 在多线程中的使用

这是 Arc 最典型的场景。

use std::sync::Arc;
use std::thread;

fn main() {
    let data = Arc::new(vec![10, 20, 30]);

    let mut handles = Vec::new();

    for i in 0..3 {
        let data = Arc::clone(&data);

        let handle = thread::spawn(move || {
            println!("thread {}: {:?}", i, data);
        });

        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}

 

posted @ 2026-10-26 20:41  苏格拉底的落泪  阅读(9)  评论(0)    收藏  举报