Câu hỏi phỏng vấn Rust
Câu hỏi

Compare Rc vs Arc in Rust

Câu trả lời

In Rust, Rc<T> and Arc<T> are both smart pointers used for reference counting, but they serve different purposes and have distinct characteristics. Here’s a detailed comparison:

Rc (Reference Counted)

Characteristics:

  • Single-threaded: Rc<T> is designed for single-threaded scenarios. It is not thread-safe and cannot be shared across multiple threads.
  • Reference Counting: It keeps track of the number of references to a value. When the last reference is dropped, the value is deallocated.
  • No Atomic Operations: Since it is not thread-safe, Rc<T> does not use atomic operations, making it slightly more performant in single-threaded contexts.

Use Cases:

  • Graph Data Structures: Useful when multiple parts of a program need to share ownership of a value, such as nodes in a graph.
  • Single-threaded Applications: Ideal for scenarios where data sharing is required within a single thread.

Example:

rust Copy
use std::rc::Rc;

fn main() {
    let data = Rc::new(42);
    let reference1 = Rc::clone(&data);
    let reference2 = Rc::clone(&data);
    println!("Data: {}", data);
}

Arc (Atomically Reference Counted)

Characteristics:

  • Thread-safe: Arc<T> is designed for multi-threaded scenarios. It is thread-safe and can be shared across multiple threads.
  • Atomic Operations: Uses atomic operations for reference counting, which ensures thread safety but comes with a performance cost compared to Rc<T>.
  • Shared Ownership: Similar to Rc<T>, it allows multiple parts of a program to share ownership of a value.

Use Cases:

  • Concurrent Applications: Ideal for scenarios where data needs to be shared across multiple threads.
  • Thread-safe Data Sharing: Useful in multi-threaded programs where safe data sharing is required.

Example:

rust Copy
use std::sync::Arc;
use std::thread;

fn main() {
    let data = Arc::new(42);
    let data_clone = Arc::clone(&data);
    let handle = thread::spawn(move || {
        println!("Data in thread: {}", data_clone);
    });
    handle.join().unwrap();
    println!("Data in main thread: {}", data);
}

Key Differences

  1. Thread Safety:
    • Rc<T> is not thread-safe and should only be used in single-threade...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What does Rust have instead of a Garbage Collector?

junior

What are the differences between String and str in Rust?

middle

Explain what is Trait in Rust? What are some use cases when you need to implement one?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào