rustadvanced
Rust Concurrency
Threads, channels and Send/Sync
7 questions
By EZ4Code Team
1. What is the function to create a thread?
std::thread::spawn
std::thread::new
std::async::spawn
std::process::spawn
Explanation: std::thread::spawn(closure) creates and starts an OS thread, returning a JoinHandle to wait for the thread to finish.
2. What does the Send trait mean?
Ownership of the type can be transferred between threads
The type can be shared by reference among multiple threads
The type can be copied
The type can be printed
Explanation: Send means the type can safely have its ownership transferred between threads; Sync means &T can be safely shared among multiple threads.
3. What does the Sync trait mean?
&T can be safely shared among multiple threads
T can be transferred between threads
T is synchronous
T cannot be used concurrently
Explanation: Sync means &T can be held by multiple threads at the same time (shared reference); if T: Sync then &T: Send.
4. What does mpsc stand for in mpsc channels?
Multiple producer, single consumer
Single producer, multiple consumer
Multiple producer, multiple consumer
Single producer, single consumer
Explanation: std::sync::mpsc is a multiple-producer, single-consumer channel; tx can be cloned to multiple producers, while rx is a single consumer.
5. What is the purpose of Mutex<T>?
Provides a mutual exclusion lock ensuring only one thread accesses the inner data at a time
A read-write lock
Atomic counter
Condition variable
Explanation: Mutex<T> acquires the lock via lock() and returns a MutexGuard, guaranteeing mutually exclusive access; it unlocks automatically when leaving scope (RAII).
6. What is the Arc<Mutex<T>> combination commonly used for?
Sharing mutable state across threads: Arc provides shared ownership, Mutex provides mutually exclusive access
Single-threaded read-only data
Asynchronous programming
Error handling
Explanation: Arc provides thread-safe shared ownership, and Mutex provides interior mutability and mutual exclusion. The combination is a common pattern for sharing mutable data across threads.
7. When are Rust's concurrency safety guarantees primarily enforced?
At compile time (via Send/Sync traits and borrow checking)
At runtime
During testing
It provides no guarantees
Explanation: Rust uses Send/Sync traits to statically guarantee no data races at compile time, known as fearless concurrency, with no runtime overhead.