Rust

Concurrency Basics

Threads, thread::spawn, move closures, channels (mpsc), Send & Sync traits, thread safety

20 interview questionsยท
Mid-Level
1

Which function should be used to create a new thread in Rust?

Answer

The thread::spawn function from the std::thread module creates a new execution thread. It takes a closure as parameter and returns a JoinHandle that allows waiting for the thread to finish using the join() method. This function is the main entry point for thread-based concurrent programming in Rust.

2

What does the join() method return when called on a JoinHandle?

Answer

The join() method returns a Result<T, E> where T is the return type of the thread's closure. If the thread completes normally, you get Ok(value). If the thread panicked, you get Err containing the panic information. This allows safely retrieving thread results or handling its errors.

3

Why use the move keyword with a closure passed to thread::spawn?

Answer

The move keyword forces the closure to take ownership of captured variables instead of borrowing them. This is essential with thread::spawn because the new thread may outlive the scope where variables are defined. Without move, the compiler refuses because it cannot guarantee that references will be valid for the thread's entire lifetime.

4

What is the role of the Send trait in Rust?

5

What is the role of the Sync trait in Rust?

+17 interview questions

Master Rust for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free