RUST Arc

ArcAtomically Reference Counted 的缩写,即"原子引用计数"。

它的作用是:让多个所有者同时持有同一份堆上数据,且可以安全地跨线程使用。

Rust 里 Arc::new(value) 内部就是把数据分配到堆上,然后返回一个指向它的智能指针。对应到 C 大概是:

c 复制代码
  // C 的手动版本
  typedef struct {
      int ref_count;   // Arc 的引用计数
      YourData data;   // 实际数据
  } ArcInner;

  ArcInner* ptr = malloc(sizeof(ArcInner));
  ptr->ref_count = 1;
  ptr->data = ...; 

Arc::clone 就是 ref_count++,Arc 被 drop 就是 ref_count--,降到 0 就 free(ptr)。

区别在于:

  • C 里你得自己维护这套逻辑,容易 double-free 或 use-after-free
  • Rust 的 Arc 把这套计数逻辑封进类型系统,编译器帮你保证正确性,且 ref_count 的加减是原子操作(线程安全)

所以 Arc 本质上就是 线程安全的、自动管理的 malloc + 引用计数。

TODO: here

相关推荐
doiito(Do It Together)7 小时前
media_agent 进化之路:把 Gliding Horse 的 Agent 超能力注入 ComfyUI,让图片生成自己“学会”优化
人工智能·架构·rust·knowledge graph
techdashen13 小时前
Arborium:把 tree-sitter 语法高亮打包成 Rust 文档生态的基础设施
开发语言·后端·rust
鹰影4715 小时前
一款AI笔记助手和远程同步的markdown笔记idea-note
人工智能·笔记·rust·typescript·react
Aspiresky15 小时前
探索Rust语言之引用
开发语言·后端·rust
techdashen15 小时前
一次 DDoS 之后的 Rust 网站复盘
开发语言·rust·ddos
独孤留白16 小时前
从C到Rust:最基础的Trait Sized
rust
techdashen16 小时前
把正确性藏进类型里:从 Go 的 io.Reader 到 Rust 的 API 设计
网络·golang·rust
前端之虎陈随易17 小时前
Rust、Golang、MoonBit 编译成 WASM,体积和速度差距有多大?
golang·rust·wasm
doiito(Do It Together)1 天前
我用 Rust 写了个 AI 媒体管家:Gliding Horse 赋能 media_agent,目标是让 ComfyUI 工作流彻底自动化
人工智能·架构·rust·媒体