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

Explain what is Send and Sync in...

Câu trả lời

In Rust, Send and Sync are marker traits that play a crucial role in ensuring thread safety in concurrent programming. Here's an explanation of each and when they are needed:

Send Trait

The Send trait indicates that ownership of a type can be safely transferred between threads. If a type implements Send, it means that instances of that type can be moved to another thread without causing data races or other concurrency issues. Most Rust types are Send by default, including primitive types and types composed entirely of Send types.

Key Points:

  • Ownership Transfer: Send allows a type to be moved from one thread to another.
  • Automatic Implementation: The Rust compiler automatically implements Send for types that are safe to transfer between threads.
  • Exceptions: Some types, like Rc<T>, are not Send because they involve non-atomic reference counting, which can lead to data races if accessed from multiple threads simultaneously[4][7][11].

Example:

rust Copy
use std::thread;

fn main() {
    let val = String::from("Hello, world!");
    let handle = thread::spawn(move || {
        println!("{}", val);
    });
    handle.join().unwrap();
}

In this example, the String type is Send, allowing it to be moved into the new thread.

Sync Trait

The Sync trait indicates that it is safe for a type to be referenced from multiple threads. If a type T is Sync, it means that &T (an immutable reference to T) can be safely shared between threads. Essentially, Sync ensures that shared references to a type do not lead to data races.

Key Points:

  • Shared References: Sync allows a type to be safely referenced from multiple threads.
  • Automatic Implementation: The Rust compiler automatically implements Sync for types that are safe to share between threads.
  • Exceptions: Types with non-thread-safe interior mutability, like Cell<T> and RefCell<T>, are not Sync because they allow mutation through shared references without synchronization[1][4][11].

Example:

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

fn main() {
    let val = Arc::new(5);
    let val_clone = Arc::clone(&val);
    let handle = thread::spawn(move || {
        println!("{}", val_clone);
    });
    handle.join().unwrap();
}

In this example, Arc<T> is Sync, allowing multiple threads to hold references to the same value.

When Do You Need Them?

Send:

  • Transferring Ownership: Use Send when you need to move ownership of a value to another ...
senior

senior

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

middle

How to implement a custom Allocator in Rust?

middle

Is String type in Rust Copy or Clone ?

junior

What are some some key features and concepts of Rust?

Bình luận

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

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