“Certified Rust Programming Expert” – A complete path from beginner to professional
Welcome back, future Rust expert! In Module One, you learned the basics of Rust. In Module Two, you learned control flow and ownership. In Module Three, you learned structs, enums, and error handling. In Module Four, you learned collections, generics, traits, modules, testing, and debugging.
Now it is time to unlock one of Rust’s greatest strengths: concurrency. Concurrency means doing many things at the same time. Imagine a bank with many cashiers serving many customers at once. Or a market with many traders selling at the same time. That is concurrency.
In this module, we will learn how to run many tasks at once using threads. We will learn how to send messages between threads. We will learn how to share data safely with Mutex and Arc. We will also learn how to work with files, read command-line arguments, use environment variables, and build command-line tools.
By the end, you will be able to write programs that do many things at once, work with the file system, and behave like real systems tools. Let’s begin!
After finishing this module, you will be able to:
Mutex and Arc.std::fs.unsafe Rust.Ada now runs a busy market stall in Lagos. She sells rice, beans, tomatoes, and peppers. Customers come from everywhere. Sometimes ten customers arrive at the same time. Ada cannot serve them all alone. She is too slow.
So Ada hires three helpers: Tunde, Chidi, and Ngozi. Now Ada can serve one customer, Tunde serves another, Chidi serves another, and Ngozi serves another. Four customers are served at the same time. The market stall becomes fast and efficient. That is concurrency.
But there is a problem. All four of them share one cash box. If two helpers try to take money from the box at the same time, they will get confused. Money might go missing. Ada needs a way to make sure only one person uses the cash box at a time. She puts a lock on the box. Only the person with the key can open it. That is a Mutex.
Ada also needs to keep records of every sale. She writes each sale in a big notebook. That notebook is a file. She writes to it and reads from it every day.
Finally, Ada wants to set up her stall automatically. She writes a small set of instructions for her helpers: “Open the stall, arrange the goods, count the money.” That is like a command-line tool. Ada gives the instructions as arguments.
Moral of the story: Concurrency lets you do many things at once. Locks keep shared things safe. Files store data. Command-line tools automate tasks.
Definition: Concurrency means doing many tasks at the same time or almost the same time.
Why it is important: Modern computers have many cores. Concurrency lets your program use them all and finish faster.
Simple explanation: Imagine a kitchen with one cook. The cook makes one dish at a time. Now imagine four cooks. They can make four dishes at once. That is concurrency.
Real-life example: A bank with many cashiers serving many customers at once.
School example: Many teachers marking different subjects at the same time.
Home example: One person washing plates while another cooks and another sweeps.
Nigerian example: A market with many traders selling at the same time. If only one trader sold, the market would be slow.
Illustration:
Without concurrency: Task A ---> Task B ---> Task C ---> Done (one after another, slow) With concurrency: Task A ---> Done Task B ---> Done Task C ---> Done (all at once, fast)
Mini summary: Concurrency means doing many things at once. It makes programs faster on modern computers.
Definition: A thread is a small worker inside your program. Each thread runs its own code at the same time as other threads.
Why it is important: Threads let your program do many things at once.
Simple explanation: Think of a restaurant. The main thread is the manager. Worker threads are the cooks, waiters, and cleaners. They all work at the same time.
Real-life example: A hospital with many doctors and nurses, each helping a different patient.
School example: Many students working on different group projects at the same time.
Home example: One family member cooks, another washes, another sets the table.
Nigerian example: A bus park with many conductors loading different buses at the same time.
Illustration:
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("Worker thread: {}", i);
thread::sleep(Duration::from_millis(500));
}
});
for i in 1..3 {
println!("Main thread: {}", i);
thread::sleep(Duration::from_millis(500));
}
handle.join().unwrap();
}
Step-by-step:
thread::spawn to create a new thread.handle.join() to wait for the thread to finish.thread::sleep to pause for a while.Mini summary: Threads are workers in your program. Use thread::spawn to create them. Use join to wait for them.
Definition: A channel is a way for threads to send messages to each other safely.
Why it is important: Threads should not share memory carelessly. Sending messages is safer.
Simple explanation: Imagine a post office. One thread writes a letter and sends it. Another thread receives the letter. The channel is the post office.
Real-life example: A walkie-talkie. One person speaks, another listens.
School example: Passing notes between students in class.
Home example: Sending a text message to a family member.
Nigerian example: A market woman sends a message to her supplier: “Bring more tomatoes.” The supplier receives it.
Illustration:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let msg = String::from("Hello from the worker!");
tx.send(msg).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
Step-by-step:
mpsc::channel().tx is the sender. rx is the receiver.tx.send(message) to send.rx.recv() to receive.move to give the sender to the thread.Mini summary: Channels let threads send messages safely. Use mpsc::channel and send/recv.
Definition: A Mutex is a lock that allows only one thread to access data at a time.
Why it is important: It prevents data races when many threads need the same data.
Simple explanation: Think of a bathroom with one key. Only the person with the key can enter. Others wait. Mutex is the key.
Real-life example: A single toilet in a house. Only one person uses it at a time.
School example: One whiteboard marker. Only one student writes at a time.
Home example: One TV remote. Only one person changes the channel at a time.
Nigerian example: One POS machine. Only one customer uses it at a time.
Illustration:
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
println!("m = {:?}", m);
}
Step-by-step:
Mutex::new(value).lock() to get access.lock() returns a Result.Mini summary: Mutex allows only one thread to access data at a time. Use lock() to get access.
Definition: Arc (Atomic Reference Counted) is a smart pointer that lets many threads share ownership of the same data.
Why it is important: Mutex alone does not let many threads own the same value. Arc adds that ability.
Simple explanation: Imagine a library book that many people can read. The book is the data. Arc is the library card that lets each reader access it.
Real-life example: A shared calendar in an office. Many people can view it.
School example: A class textbook that all students can read.
Home example: A family photo album that everyone can look at.
Nigerian example: A community notice board that everyone can read.
Illustration:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..5 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
Step-by-step:
Arc::new(Mutex::new(value)).Arc::clone.lock().Mini summary: Arc allows many threads to share ownership. Combine with Mutex for safe sharing. Use Arc::clone.
Definition: Files store data on your computer even after the program stops. Rust can read and write files.
Why it is important: Programs need to save data, load settings, and store logs.
Simple explanation: A file is like a notebook. You can write in it and read from it later.
Real-life example: Saving a document on your computer.
School example: Writing homework in an exercise book and reading it later.
Home example: A shopping list on the fridge.
Nigerian example: A trader’s ledger book where all sales are recorded.
Illustration:
use std::fs;
use std::io::Write;
fn main() -> std::io::Result<()> {
// Write to a file
let mut file = fs::File::create("sales.txt")?;
writeln!(file, "Rice: 500")?;
writeln!(file, "Beans: 300")?;
// Read from a file
let content = fs::read_to_string("sales.txt")?;
println!("File contents:\n{}", content);
Ok(())
}
Step-by-step:
fs::File::create to make a new file.writeln! to write lines.fs::read_to_string to read the whole file.Result to handle errors with ?.Mini summary: Files store data. Use std::fs to read and write. Always handle errors with Result.
Definition: Command-line arguments are extra words you type after the program name to give it information.
Why it is important: They let users control what the program does without changing the code.
Simple explanation: Like telling a taxi driver where to go: “Take me to Yaba.” The destination is the argument.
Real-life example: Ordering food: “Give me two plates of rice.” The number is the argument.
School example: A teacher saying: “Open your book to page 42.” Page 42 is the argument.
Home example: Telling the generator: “Run for 2 hours.” 2 hours is the argument.
Nigerian example: Telling a bus conductor: “I am going to Ikeja.” Ikeja is the argument.
Illustration:
use std::env;
fn main() {
let args: Vec = env::args().collect();
if args.len() < 2 {
println!("Please provide a name.");
return;
}
println!("Hello, {}!", args[1]);
}
// Run with: cargo run Ada
// Output: Hello, Ada!
Step-by-step:
std::env.env::args() to get the arguments..collect()..len().args[1].Mini summary: Command-line arguments let users pass information to your program. Use std::env::args().
Definition: Environment variables are settings stored by the operating system that programs can read.
Why it is important: They let you change program behaviour without changing code. They also keep secrets safe.
Simple explanation: Like a school’s rule book. Every teacher reads the same rules.
Real-life example: The temperature setting on an air conditioner.
School example: The school’s daily schedule posted on the wall.
Home example: The family rules on the fridge.
Nigerian example: A market association’s rules that all traders follow.
Illustration:
use std::env;
fn main() {
match env::var("HOME") {
Ok(home) => println!("Your home folder is: {}", home),
Err(_) => println!("HOME not set"),
}
}
Step-by-step:
std::env.env::var("NAME") to read.Result.Ok and Err with match.Mini summary: Environment variables are system settings. Use env::var to read them. Always handle errors.
Definition: A command-line tool is a program you run from the terminal to do a specific job.
Why it is important: They are fast, simple, and powerful. Many professional tools are command-line tools.
Simple explanation: A tool like a hammer. You pick it up and use it for a job.
Real-life example: ls lists files. cp copies files.
School example: A calculator for maths.
Home example: A blender for smoothies.
Nigerian example: A POS machine for payments.
Illustration:
use std::env;
use std::fs;
fn main() {
let args: Vec = env::args().collect();
if args.len() < 3 {
println!("Usage: {} ", args[0]);
return;
}
match args[1].as_str() {
"read" => {
match fs::read_to_string(&args[2]) {
Ok(content) => println!("{}", content),
Err(e) => println!("Error: {}", e),
}
}
"write" => {
match fs::write(&args[2], "Hello, file!") {
Ok(_) => println!("Written to {}", args[2]),
Err(e) => println!("Error: {}", e),
}
}
_ => println!("Unknown command: {}", args[1]),
}
}
Step-by-step:
env::args().match on the first argument.match.Mini summary: Command-line tools are powerful. Use arguments, match, and file functions. Handle errors carefully.
unsafe RustDefinition: unsafe is a keyword that lets you do things Rust normally prevents, like raw pointer access.
Why it is important: Sometimes you need to talk directly to hardware or use C libraries.
Simple explanation: Think of a locked room. Normally you cannot enter. With unsafe, you can, but you must be very careful.
Real-life example: A doctor entering a restricted hospital area. Only trained people should go in.
School example: Only the head teacher can enter the staff room.
Home example: Only adults can use the gas cooker.
Nigerian example: Only authorised traders can enter the central bank vault.
Illustration:
fn main() {
let mut num = 5;
let r1 = &num as *const i32;
unsafe {
println!("r1 points to: {}", *r1);
}
}
Step-by-step:
as *const T to make a raw pointer.unsafe { }.*r1.unsafe only when necessary.Mini summary: unsafe lets you do dangerous things. Use it only when needed. Document why.
Definition: Async programming lets your program wait for slow tasks (like network or files) without blocking other work.
Why it is important: It makes programs that handle many users fast and efficient.
Simple explanation: Imagine a waiter taking orders from many tables. While the kitchen cooks one order, the waiter serves another table. No time is wasted.
Real-life example: A restaurant with one waiter serving many tables.
School example: One teacher helping many students at the same time.
Home example: Cooking rice while watching the stew.
Nigerian example: One POS operator serving many customers, one at a time, without waiting idly.
Illustration:
async fn fetch_data() -> String {
String::from("Data loaded")
}
fn main() {
// Async needs a runtime, e.g. tokio.
// This is a simple introduction.
}
Step-by-step:
async fn for slow tasks..await to wait for the result.tokio.Mini summary: Async lets you handle slow tasks without blocking. Use async and .await. You need a runtime.
Definition: Mistakes happen. Knowing them helps you avoid them.
Why it is important: Concurrency is powerful but tricky. Rust helps, but you must be careful.
Simple explanation: Like driving a car. It is fast, but you must follow rules.
Real-life example: Two people trying to use the same ATM at the same time.
School example: Two students writing on the same whiteboard at the same time.
Home example: Two people trying to enter the same door at the same time.
Nigerian example: Two traders selling the same item and confusing the customer.
Table of common mistakes:
| Mistake | What happens | Rust’s help |
|---|---|---|
| Forgetting to join threads | Program may exit early | handle.join() |
| Forgetting to lock before using shared data | Data race | Compiler error |
Using Arc without Mutex | Cannot mutate | Compiler error |
| Deadlock (two locks waiting on each other) | Program hangs | Careful design |
| Ignoring file errors | Panic or wrong result | Use Result and ? |
Using unsafe carelessly | Undefined behaviour | You must be careful |
Mini summary: Concurrency has pitfalls. Rust catches many. Read error messages. Be careful with locks and threads.
Definition: Best practices are good habits that make your code clean and safe.
Why it is important: Concurrency and systems code must be reliable.
Simple explanation: Like a pilot following a checklist before takeoff.
Real-life example: A surgeon washing hands before an operation.
School example: Writing your name on every exam paper.
Home example: Turning off the gas after cooking.
Nigerian example: A trader counting money twice before giving change.
List of best practices:
Arc<Mutex<T>> for shared mutable data.Result.? to propagate errors cleanly.unsafe.cargo clippy to catch common mistakes.Mini summary: Follow best practices. They keep your concurrent code safe and reliable.
Let’s write a program that uses threads, channels, files, and error handling.
Program: Count words in many files using threads
use std::fs;
use std::sync::mpsc;
use std::thread;
fn main() {
let files = vec!["file1.txt", "file2.txt", "file3.txt"];
let (tx, rx) = mpsc::channel();
for file in files {
let tx = tx.clone();
thread::spawn(move || {
match fs::read_to_string(file) {
Ok(content) => {
let count = content.split_whitespace().count();
tx.send((file, count)).unwrap();
}
Err(e) => {
tx.send((file, 0)).unwrap();
eprintln!("Error reading {}: {}", file, e);
}
}
});
}
drop(tx); // close original sender
for (file, count) in rx {
println!("{}: {} words", file, count);
}
}
Explanation:
Mini summary: This program combines threads, channels, files, and error handling. It is a real-world example of concurrency.
Let’s build a small tool that counts words in files given on the command line.
use std::env;
use std::fs;
use std::sync::mpsc;
use std::thread;
fn main() {
let args: Vec = env::args().skip(1).collect();
if args.is_empty() {
println!("Usage: wordcount ...");
return;
}
let (tx, rx) = mpsc::channel();
for file in args {
let tx = tx.clone();
thread::spawn(move || {
match fs::read_to_string(&file) {
Ok(content) => {
let count = content.split_whitespace().count();
tx.send((file, count)).unwrap();
}
Err(_) => {
tx.send((file, 0)).unwrap();
}
}
});
}
drop(tx);
let mut total = 0;
for (file, count) in rx {
println!("{}: {} words", file, count);
total += count;
}
println!("Total: {} words", total);
}
Explanation:
env::args().skip(1) gets all file names after the program name.Mini summary: This tool combines command-line arguments, threads, channels, and files. It is a real systems programming example.
| Word | Simple Definition |
|---|---|
| Concurrency | Doing many tasks at the same time. |
| Thread | A worker inside your program that runs code. |
| Channel | A safe way for threads to send messages. |
| Mutex | A lock that allows only one thread to access data at a time. |
| Arc | A smart pointer for shared ownership across threads. |
| File | Stored data on your computer. |
| Command-line argument | Extra words typed after a program name. |
| Environment variable | A system setting programs can read. |
| Command-line tool | A program run from the terminal. |
unsafe | A keyword that lets you do dangerous things. |
| Async | Doing slow tasks without blocking others. |
| Deadlock | Two threads waiting on each other forever. |
| Data race | Two threads accessing the same data carelessly. |
join | Wait for a thread to finish. |
spawn | Create a new thread. |
Arc<Mutex<T>>.std::fs.env::args().env::var().unsafe: Use only when necessary. Document why.Result for IO.std::thread.thread::spawn(|| { ... }).handle.join().unwrap() to wait.Example:
use std::thread;
let handle = thread::spawn(|| {
println!("Hello from a thread!");
});
handle.join().unwrap();
std::sync::mpsc.let (tx, rx) = mpsc::channel();.tx for each thread.tx.send(value) inside the thread.rx.recv() or for msg in rx in the main thread.Example:
use std::sync::mpsc;
use std::thread;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("Hello").unwrap();
});
println!("{}", rx.recv().unwrap());
std::fs.fs::read_to_string("file.txt").Result.match or ? to handle errors.Example:
use std::fs;
match fs::read_to_string("data.txt") {
Ok(content) => println!("{}", content),
Err(e) => println!("Error: {}", e),
}
std::env.env::args().collect::<Vec<String>>().args[1], args[2], etc.args.len() to avoid errors.Example:
use std::env; let args: Vec= env::args().collect(); if args.len() > 1 { println!("Hello, {}!", args[1]); }
Arc type uses atomic operations, which are safe across threads.Mutex releases the lock automatically when it goes out of scope.unsafe keyword does not turn off all checks, only some.Arc stands for “Atomic Reference Counted”?Mutex stands for “Mutual Exclusion”?mpsc stands for “Multi-Producer, Single-Consumer”?Result for safety?env::args() includes the program name as the first item?unsafe is used in many standard library internals?std::fs.env::args().env::var().unsafe only when necessary.Result.Arc without Mutex when mutating.unsafe without a good reason.Arc<Mutex<T>> for shared mutable data.Result.? to propagate errors.unsafe.cargo clippy.
Main Thread
|
+--> Worker Thread 1 ---> Task A
|
+--> Worker Thread 2 ---> Task B
|
+--> Worker Thread 3 ---> Task C
|
V
Join all threads
|
V
Program ends
Thread 1 (Sender)
|
V
[ Channel ]
|
V
Thread 2 (Receiver)
Thread 1 ---> lock() ---> Use data ---> unlock()
Thread 2 ---> wait... |
V
(when unlocked)
|
V
Thread 2 ---> lock() ---> Use data ---> unlock()
Arc> | +--> Thread 1: lock, change, unlock | +--> Thread 2: lock, change, unlock | +--> Thread 3: lock, change, unlock | V Final value
Program
|
+--> fs::File::create("file.txt")
| |
| V
| writeln!(file, "data")
|
+--> fs::read_to_string("file.txt")
|
V
Ok(content) or Err(e)
Module One: Rust Foundations
|
V
Module Two: Control Flow and Ownership
|
V
Module Three: Custom Types and Error Handling
|
V
Module Four: Collections, Generics, and Traits
|
V
Module Five: Concurrency and Systems Programming
|
V
Module Six: Professional Rust and Capstone
|
V
Certified Rust Programming Expert 🎉
| Feature | Threads | Channels | Mutex |
|---|---|---|---|
| Purpose | Run code in parallel | Send messages | Lock shared data |
| Safety | Safe with ownership | Very safe | Safe with care |
| Use case | Parallel tasks | Communication | Shared state |
| Feature | Mutex | Arc |
|---|---|---|
| Purpose | Lock data | Share ownership |
| Used with | Threads | Threads |
| Together | Arc<Mutex<T>> for shared mutable data | |
| Operation | Function | Returns |
|---|---|---|
| Read | fs::read_to_string | Result<String> |
| Write | fs::write | Result<()> |
| Create | fs::File::create | Result<File> |
| Feature | Safe Rust | Unsafe Rust |
|---|---|---|
| Memory safety | Guaranteed | You must ensure |
| Use case | Most programs | Hardware, FFI |
| Keyword | Default | unsafe { } |
Lesson 1: Concurrency means doing many tasks at once.
Lesson 2: Threads are workers in your program. Use thread::spawn.
Lesson 3: Channels let threads send messages safely.
Lesson 4: Mutex allows only one thread to access data at a time.
Lesson 5: Arc allows shared ownership across threads.
Lesson 6: Files store data. Use std::fs.
Lesson 7: Command-line arguments come from env::args().
Lesson 8: Environment variables come from env::var().
Lesson 9: Command-line tools combine arguments and logic.
Lesson 10: unsafe lets you do dangerous things carefully.
Lesson 11: Async lets you handle slow tasks without blocking.
Lesson 12: Common mistakes include forgetting to join threads and deadlocks.
Lesson 13: Best practices: prefer channels, keep locks short, handle errors.
Lesson 14: Combine threads, channels, and files in a multi-threaded file processor.
Lesson 15: Build a command-line tool with concurrency.
Congratulations! You have finished Module Five of the Certified Rust Programming Expert course. You learned how to do many things at once with threads. You learned how to send messages between threads with channels. You learned how to share data safely with Mutex and Arc. You learned how to read and write files. You learned how to use command-line arguments and environment variables. You built a command-line tool. You also learned about unsafe Rust and async programming. You saw many examples from Nigeria and everyday life. You now know common mistakes and best practices. Most importantly, you can write programs that do many things at once and talk to the system. Keep practising, and you will become a Certified Rust Programming Expert!
fs::read_to_string.env::args().env::var().unsafe? A keyword that lets you do dangerous things carefully.Match the word to its definition.
| Word | Definition |
|---|---|
| 1. Thread | A. Safe message sending. |
| 2. Channel | B. Lock for shared data. |
| 3. Mutex | C. Worker in a program. |
| 4. Arc | D. Stored data on disk. |
| 5. File | E. Shared ownership. |
Answers: 1-C, 2-A, 3-B, 4-E, 5-D
Arc<Mutex<i32>>.fs::read_to_string.env::args().Title: “Build a Multi-Threaded Word Counter”
Instructions: In groups of 3–4, write a Rust program that takes several file names from the command line. Each file is processed in its own thread. Each thread counts the words and sends the result back through a channel. The main thread prints the total. Share your program with the class.
Goal: Practice threads, channels, files, and arguments.
Task: Write a Rust program that spawns three threads. Each thread prints a different message five times. Use join to wait for all of them. Then run it and observe the output.
Hint: Use thread::spawn and handle.join().
Project: “My File Logger”
Write a Rust program that:
log.txt.Result and ? to handle errors.Example output:
Log started at 10:00 Log started at 10:05 Log started at 10:12
Assignment: Create a new Cargo project called file_stats. In main.rs, write a program that:
Result.Submit: Your main.rs file and a screenshot of the program running.
std::fs.env::args().env::var().unsafe only when necessary.Result.unsafe?In Module Six, we will finish the course. We will learn about:
rustdoc.To prepare, make sure you have completed the practical assignment and can write programs with threads, channels, files, and arguments. Review your notes on Arc and Mutex. Bring your curiosity!
See you in Module Six!
End of Module Five – Certified Rust Programming Expert