zoukankan      html  css  js  c++  java
  • How Arc works in Rust

    The Atomic Reference Counter (Arc) type is a smart pointer that lets you share immutable data across threads in a thread-safe way. I couldn’t find any good articles explaining how it works, so that’s what I’ll attempt to do here. The first section is an introduction on how and why to use Arc; if you already know this and just want to know how it actually works, skip to the second section titled; “How does it work”.

    Why would you need to use Arc?

    This code will not compile; We will get an error saying that the reference to foo outlives foo itself. This is because foo gets dropped at the end of the main function and then the dropped value will try to be accessed 20 milliseconds later in the spawned thread. This is where Arc comes in. The atomic reference counter essentially makes sure that the foo type will not be dropped until all references to it have ceased — So that even after the main function resolves, foo will still exist. Now consider this example;

    In this example we can now, reference foo in the thread and also access it’s value after the thread has been spawned.

    How does it work?

    When you call let bar = Arc::clone(&foo), you are taking a reference to foo, dereferencing foo (which is a pointer to the data on the heap remember), then going to the address that foo points to, finding the values there (which is vec![0] and the atomic_counter), incrementing the atomic counter by one and then storing the address that points to the vec![0] in bar.

    When foo or bar fall out of scope, and Arc::drop() is then consequently called, the atomic_counter is decremented by one. If Arc::drop() finds that the atomic counter is equal to 0, then the data that it points to on the heap (vec![0] and atomic_counter) are cleared up and erased from the heap.

    An atomic counter is a type that lets you mutate and increment its value in a thread safe way; Each operation on an atomic type is completed fully before other operations are allowed; Hence, the name atomic (which means indivisible).

    It is important to note that Arc can only contain immutable data. This is because Arc cannot guarantee safety from data-races, should two threads try to mutate the value contained within at the same time. If you wish to mutate data, you should encapsulate a Mutex guard inside the Arc type.

    So why do these things make Arc thread safe?

    So what is the point of Rc and why not use Arc for everything?

  • 相关阅读:
    powerdesigner 字段添加注释和默认值
    springboot集成enchance
    判断字段数据什么数据类型
    springboot打成jar包涉及到的linux命令
    springdatajpa添加完modle之后立即返回id
    阿里云上部署环境
    STS 启动之后, "Initializing Java Tooling" 一直卡住问题解决
    C#访问MongoDB数据
    MongoDB开发学习(1)开天辟地,经典入门
    Step by Step 設定 TFS 2012 Create Team Project 權限
  • 原文地址:https://www.cnblogs.com/dream397/p/14200449.html
Copyright © 2011-2022 走看看