Fearless Concurrency with Threads
Dive into Rust's primitives for concurrent programming, including threads and message passing, ensuring data race freedom.
Intro to Concurrency
Welcome to Fearless Concurrency with Threads! In this lesson, we'll learn how to make your Rust programs do multiple things at once.
Concurrency means executing multiple computations seemingly at the same time. It's vital for responsive applications and utilizing modern multi-core processors.
- Threads are lightweight units of execution within a program.
- Each thread can run a separate part of your code.
- Rust's ownership system helps prevent common concurrency bugs.
Creating Your First Thread
Rust provides std::thread::spawn to create new threads. You pass it a closure (an anonymous function) that contains the code the new thread should run.
Try running this example to see threads in action:
use std::thread;
use std::time::Duration;
fn main() {
println!("Hello from the main thread!");
thread::spawn(|| {
for i in 1..=5 {
println!("Hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..=3 {
println!("Hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
}All lessons in this course
- Box, Rc, and Arc Smart Pointers
- Interior Mutability: RefCell, Cell
- Fearless Concurrency with Threads