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?

  • 相关阅读:
    windows下 删除指定文件夹里面一周前的所有文件和文件夹的bat
    freeswitch 把SIP注册信息数据库从SQLITE 改为MYSQL的方法
    memcached+Mysql(主从)
    Linux下的MySQL主主复制
    RabbitMQ php 使用
    如果你写PHP, 请多注意自己是否有良好的习惯
    MySQL主从配置的一些总结
    Mongodb与mysql语法比较
    Yii框架tips
    Windows下Python添加MySQLdb扩展模块
  • 原文地址:https://www.cnblogs.com/dream397/p/14200449.html
Copyright © 2011-2022 走看看