Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Arc work in Rust

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces how Arc works in Rust. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

The atomic reference count (Arc) type is a smart pointer that allows you to share immutable data between threads in a thread-safe manner. I haven't found an article that can well explain how it works, so I decided to try to write one.

The first part is about how to use Arc and why to use Arc;. If you already know this part and just want to know how it works, you can skip to the second part: "how does it work (How does it work)".

Why do you need to use Arc? When you try to share data between threads, you need the Arc type to ensure that the life cycle of the shared type is as long as the longest running thread. Consider the following example:

Use std::thread;use std::time::Duration;fn main () {let foo = vec! [0]

/ / creation of foo here thread::spawn (| | {

Thread::sleep (Duration::from_millis (20)); println! ("{:?}", & foo);});}

/ / foo gets dropped here

/ / wait 20 milliseconds

/ / try to print foo

This code cannot be compiled. We get an error saying that the reference to foo lives longer than the foo itself. This is because foo is drop at the end of the main function, and the discarded value is attempted to be accessed in the generated thread 20 milliseconds later. This is what Arc is for. Atomic reference counting ensures that the foo type is not discarded until all references to it end-- so foo still exists even after the end of the main function. Now consider the following example:

Use std::thread;use std::sync::Arc;use std::time::Duration;fn main () {

Let foo = Arc::new (vec! [0]); let bar = Arc::clone (& foo)

Thread::spawn (move | | {

Thread::sleep (Duration::from_millis (20)); println! ("{:?}", * bar);})

Println! ("{:?}", foo);}

In this example, we can reference foo in the (main) thread and can also access its value after the (child) thread has been generated.

How does it work? Now that you know how to use Arc, let's discuss how it works. When you call let foo = Arc::new (vec! [0]), you create both a vec! [0] and an atomic reference count with a value of 1, and store them all in the same location on the heap (next to each other). The pointer to this data on the heap is stored in foo. Therefore, foo is made up of pointers to an object that contains vec! [0] and atomic counts.

When you call let bar = Arc::clone (& foo), you are getting a reference to foo, dereferencing foo (a pointer to data stored on the heap), then finding the address that foo points to, finding the value stored in it (vec! [0] and atomic count), adding one to the atomic count, and finally saving the pointer to vec! [0] in bar.

When foo or bar leaves scope, Arc::drop () is called and the atomic count is minus one. If Arc::drop () finds that the atomic count is equal to 0, then the data on the heap it points to (vec! [0] and atomic count) will be cleaned and erased from the heap.

Atomic counting is a type that allows you to modify and increase its value in a thread-safe way; before other operations on atomic types are allowed, the previous atomic type operations must be completed; therefore, they are called atomic (atomic) (that is, indivisible) (operations).

It is important to note that Arc can only contain immutable data. This is because if two threads try to modify the contained values at the same time, Arc cannot guarantee against data contention. If you want to modify the data, you should encapsulate a mutex protection (Mutex guard) inside the Arc type.

Why do these things make Arc thread-safe? Arc is thread-safe because it ensures to the compiler that the reference to the data is at least as long as the data itself. This is because every time you create a reference to the data on the heap, the atomic count increases by one, and the data is discarded only when the atomic count is equal to zero (every time a reference leaves scope, the atomic count is minus one)-the difference between Arc and a normal Rc (reference count) is the atomic count.

So much for sharing about how Arc works in Rust. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 209

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report