You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Rust makes concurrent programming safer through its ownership and type system. This lesson covers threads, message passing, shared state, async/await, and the broader Rust ecosystem.
Rust provides OS-level threads through the standard library:
use std::thread;
use std::time::Duration;
let handle = thread::spawn(|| {
for i in 1..5 {
println!("spawned thread: {i}");
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..3 {
println!("main thread: {i}");
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap(); // wait for the spawned thread to finish
Use move to transfer ownership of captured variables:
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("data: {data:?}");
});
// data is no longer accessible here — it was moved
handle.join().unwrap();
Rust uses two marker traits to enforce thread safety at compile time:
| Trait | Meaning |
|---|---|
| Send | A type can be transferred to another thread |
| Sync | A type can be shared between threads via references |
Most types are Send and Sync automatically. Notable exceptions:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.