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?

  • 相关阅读:
    [CQOI2015]选数
    利用匈牙利算法&HopcroftKarp算法解决二分图中的最大二分匹配问题 例poj 1469 COURSES
    玩家死亡,屏幕灰白效果实现
    Bool值相加
    (转)D3D性能优化
    Flash AS3视频教程
    Accurately Profiling Direct3D API Calls (Direct3D 9)
    菲涅尔反射
    sscanf时用到郁闷问题
    如何精确测量程序运行时间(转)
  • 原文地址:https://www.cnblogs.com/dream397/p/14200449.html
Copyright © 2011-2022 走看看