Concurrency and Parallelism
Introduction
In this chapter, we will explore the concepts of concurrency and parallelism in Rust. Concurrency refers to the ability of a program to perform multiple tasks simultaneously, while parallelism refers to the ability of a program to execute multiple tasks at the same time using multiple processing units.
Key Concepts
-
Threads: Rust provides a built-in support for threads, which allow a program to execute multiple tasks concurrently.
-
Mutex: A mutex (short for mutual exclusion) is a mechanism that allows only one thread to access a shared resource at a time.
-
Channels: Channels are a way for threads to communicate with each other, allowing them to send and receive data.
Practical Examples
// Creating a new thread
use std::thread;
fn main() {
thread::spawn(|| {
println!("Hello from new thread!");
});
}
In this example, we create a new thread using the thread::spawn function, which takes a closure as an argument. The closure is executed in a new thread.
Using Mutex
use std::sync::{Arc, Mutex};
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter_clone = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter_clone.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
}
In this example, we use a mutex to protect a shared resource (a counter) from concurrent access. We create multiple threads that increment the counter, and use a mutex to ensure that only one thread can access the counter at a time.