Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Certified Rust Programming Expert · Lesson 6 of 7

Module Five

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
6
Certified Rust Programming Expert – Module Five

Module Five: Concurrency and Systems Programming – Doing Many Things at Once and Talking to the System

“Certified Rust Programming Expert” – A complete path from beginner to professional

Module Introduction

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!

Learning Objectives

After finishing this module, you will be able to:

  • Explain what concurrency is and why it matters.
  • Create and join threads in Rust.
  • Use message passing with channels.
  • Share data safely with Mutex and Arc.
  • Read and write files using std::fs.
  • Read command-line arguments.
  • Use environment variables.
  • Build simple command-line tools.
  • Understand the basics of unsafe Rust.
  • Recognize common mistakes and best practices.
  • Complete a mini project and practical assignment.

Warm-up Story: Ada’s Busy Market Stall

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.

Main Lessons

Lesson 1: What is Concurrency?

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.

Lesson 2: Threads – Workers in Your Program

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:

  • Use thread::spawn to create a new thread.
  • Pass a closure with the code the thread should run.
  • Use handle.join() to wait for the thread to finish.
  • Use 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.

Lesson 3: Message Passing with Channels

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:

  • Create a channel with mpsc::channel().
  • tx is the sender. rx is the receiver.
  • Use tx.send(message) to send.
  • Use rx.recv() to receive.
  • Use move to give the sender to the thread.

Mini summary: Channels let threads send messages safely. Use mpsc::channel and send/recv.

Lesson 4: Sharing Data with Mutex

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:

  • Create with Mutex::new(value).
  • Use lock() to get access.
  • lock() returns a Result.
  • When the lock goes out of scope, it is released automatically.

Mini summary: Mutex allows only one thread to access data at a time. Use lock() to get access.

Lesson 5: Shared Ownership with Arc

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:

  • Wrap the value: Arc::new(Mutex::new(value)).
  • Clone the Arc for each thread with Arc::clone.
  • Lock inside the thread with lock().
  • Join all threads.

Mini summary: Arc allows many threads to share ownership. Combine with Mutex for safe sharing. Use Arc::clone.

Lesson 6: Working with Files – Reading and Writing

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:

  • Use fs::File::create to make a new file.
  • Use writeln! to write lines.
  • Use fs::read_to_string to read the whole file.
  • Return Result to handle errors with ?.

Mini summary: Files store data. Use std::fs to read and write. Always handle errors with Result.

Lesson 7: Command-Line Arguments

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:

  • Import std::env.
  • Use env::args() to get the arguments.
  • Collect them into a vector with .collect().
  • Check the length with .len().
  • Access the first real argument with args[1].

Mini summary: Command-line arguments let users pass information to your program. Use std::env::args().

Lesson 8: Environment Variables

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:

  • Import std::env.
  • Use env::var("NAME") to read.
  • It returns Result.
  • Handle Ok and Err with match.

Mini summary: Environment variables are system settings. Use env::var to read them. Always handle errors.

Lesson 9: Building a Simple Command-Line Tool

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:

  • Read arguments with env::args().
  • Check that enough arguments are given.
  • Use match on the first argument.
  • Do the action (read or write).
  • Handle errors with match.

Mini summary: Command-line tools are powerful. Use arguments, match, and file functions. Handle errors carefully.

Lesson 10: Introduction to unsafe Rust

Definition: 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:

  • Use as *const T to make a raw pointer.
  • Wrap the dangerous code in unsafe { }.
  • Dereference with *r1.
  • Use unsafe only when necessary.

Mini summary: unsafe lets you do dangerous things. Use it only when needed. Document why.

Lesson 11: Async Programming – A Simple Introduction

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:

  • Write async fn for slow tasks.
  • Use .await to wait for the result.
  • You need an async runtime like tokio.
  • Start simple. Async is advanced.

Mini summary: Async lets you handle slow tasks without blocking. Use async and .await. You need a runtime.

Lesson 12: Common Mistakes with Concurrency

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:

MistakeWhat happensRust’s help
Forgetting to join threadsProgram may exit earlyhandle.join()
Forgetting to lock before using shared dataData raceCompiler error
Using Arc without MutexCannot mutateCompiler error
Deadlock (two locks waiting on each other)Program hangsCareful design
Ignoring file errorsPanic or wrong resultUse Result and ?
Using unsafe carelesslyUndefined behaviourYou must be careful

Mini summary: Concurrency has pitfalls. Rust catches many. Read error messages. Be careful with locks and threads.

Lesson 13: Best Practices for Concurrency and Systems Programming

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:

  • Prefer message passing (channels) over shared memory when possible.
  • Use Arc<Mutex<T>> for shared mutable data.
  • Keep locks short. Do not hold locks while doing slow work.
  • Always join threads or use scoped threads.
  • Handle all file and IO errors with Result.
  • Use ? to propagate errors cleanly.
  • Document why you use unsafe.
  • Test concurrent code carefully.
  • Use cargo clippy to catch common mistakes.
  • Read the Rust concurrency documentation.

Mini summary: Follow best practices. They keep your concurrent code safe and reliable.

Lesson 14: Putting It All Together – A Multi-Threaded File Processor

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:

  • We create a channel for messages.
  • We spawn one thread per file.
  • Each thread reads its file and sends the word count.
  • The main thread receives and prints results.
  • We drop the original sender to end the loop.

Mini summary: This program combines threads, channels, files, and error handling. It is a real-world example of concurrency.

Lesson 15: Building a Simple Command-Line Tool with 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.
  • Each file is processed in its own thread.
  • Results are sent back through a channel.
  • The main thread sums the counts.

Mini summary: This tool combines command-line arguments, threads, channels, and files. It is a real systems programming example.

Key Vocabulary

WordSimple Definition
ConcurrencyDoing many tasks at the same time.
ThreadA worker inside your program that runs code.
ChannelA safe way for threads to send messages.
MutexA lock that allows only one thread to access data at a time.
ArcA smart pointer for shared ownership across threads.
FileStored data on your computer.
Command-line argumentExtra words typed after a program name.
Environment variableA system setting programs can read.
Command-line toolA program run from the terminal.
unsafeA keyword that lets you do dangerous things.
AsyncDoing slow tasks without blocking others.
DeadlockTwo threads waiting on each other forever.
Data raceTwo threads accessing the same data carelessly.
joinWait for a thread to finish.
spawnCreate a new thread.

Important Concepts

  • Concurrency: Doing many tasks at once.
  • Threads: Workers inside your program.
  • Message passing: Threads send messages safely.
  • Shared state: Use Arc<Mutex<T>>.
  • Files: Store and load data with std::fs.
  • Arguments: Read with env::args().
  • Environment: Read with env::var().
  • Command-line tools: Combine arguments, files, and logic.
  • unsafe: Use only when necessary. Document why.
  • Async: Handle slow tasks without blocking.
  • Error handling: Always use Result for IO.

Step-by-step Explanations

How to spawn and join a thread step by step

  1. Import std::thread.
  2. Call thread::spawn(|| { ... }).
  3. Store the handle in a variable.
  4. Use handle.join().unwrap() to wait.

Example:

  use std::thread;

  let handle = thread::spawn(|| {
      println!("Hello from a thread!");
  });

  handle.join().unwrap();
  

How to use a channel step by step

  1. Import std::sync::mpsc.
  2. Create with let (tx, rx) = mpsc::channel();.
  3. Clone tx for each thread.
  4. Use tx.send(value) inside the thread.
  5. Use 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());
  

How to read a file step by step

  1. Import std::fs.
  2. Use fs::read_to_string("file.txt").
  3. It returns Result.
  4. Use 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),
  }
  

How to read command-line arguments step by step

  1. Import std::env.
  2. Use env::args().collect::<Vec<String>>().
  3. The first item is the program name.
  4. Use args[1], args[2], etc.
  5. Check args.len() to avoid errors.

Example:

  use std::env;

  let args: Vec = env::args().collect();
  if args.len() > 1 {
      println!("Hello, {}!", args[1]);
  }
  

Real-life Examples

  • Web servers: Handle many users at once with threads.
  • Video games: Run physics, graphics, and sound on different threads.
  • Data processing: Process many files at the same time.
  • Backup tools: Read and write files.
  • Log readers: Read files and count lines.

Nigerian Examples

  • POS network: Many POS machines sending transactions to a central server.
  • Bank servers: Handling many withdrawals at once.
  • Market records: A trader’s ledger file.
  • Bus booking: Command-line tool to book seats.
  • Electricity billing: Reading meter files and calculating bills.

Fun Examples Children Can Relate To

  • Video game: One thread moves the character, one plays music, one loads levels.
  • Robot: One thread moves the arms, one reads sensors, one talks.
  • Chat app: One thread sends messages, one receives them.
  • School quiz: One thread times the quiz, one checks answers.
  • Treasure hunt: Many threads looking for treasure in different places.

Everyday Examples

  • Cooking: Boiling rice while frying stew.
  • Laundry: Washing while drying.
  • School: Reading while listening to music.
  • Commute: Listening to a podcast while walking.
  • Home: Charging phone while watching TV.

Parent Tips

  • Encourage your child to think about doing things at the same time.
  • Let them make mistakes. Concurrency is tricky.
  • Use everyday examples (cooking, laundry) to explain concurrency.
  • Set a small daily coding time. Consistency helps.
  • Celebrate small wins, like making two threads run.
  • Be patient. Concurrency takes time to understand.
  • Ask them to explain their code out loud.
  • Keep it fun. Use games and stories.
  • Remind them that even expert programmers find concurrency hard.
  • Encourage them to read Rust’s official concurrency guide.

Interesting Facts

  • Rust prevents data races at compile time.
  • Rust’s concurrency model is inspired by Erlang and Go.
  • The Arc type uses atomic operations, which are safe across threads.
  • Rust’s Mutex releases the lock automatically when it goes out of scope.
  • Rust’s unsafe keyword does not turn off all checks, only some.
  • Async Rust is used by many web servers and network tools.
  • The Rust compiler will not let you forget to join a thread if you use scoped threads.
  • Rust’s channels are inspired by Hoare’s communicating sequential processes (CSP).

Did You Know?

  • Did you know that Rust can run many threads without a garbage collector?
  • Did you know that Arc stands for “Atomic Reference Counted”?
  • Did you know that Mutex stands for “Mutual Exclusion”?
  • Did you know that mpsc stands for “Multi-Producer, Single-Consumer”?
  • Did you know that Rust’s file functions return Result for safety?
  • Did you know that env::args() includes the program name as the first item?
  • Did you know that async Rust uses a “runtime” like Tokio or async-std?
  • Did you know that unsafe is used in many standard library internals?

Remember This

  • Concurrency means doing many tasks at once.
  • Threads are workers inside your program.
  • Channels let threads send messages safely.
  • Mutex allows only one thread at a time.
  • Arc allows shared ownership across threads.
  • Files store data with std::fs.
  • Arguments come from env::args().
  • Environment variables come from env::var().
  • Command-line tools combine arguments and logic.
  • Use unsafe only when necessary.
  • Always handle errors with Result.

Common Mistakes

  • Forgetting to join threads.
  • Forgetting to lock before using shared data.
  • Using Arc without Mutex when mutating.
  • Creating deadlocks with multiple locks.
  • Ignoring file errors.
  • Using unsafe without a good reason.
  • Forgetting to drop the original sender in a channel loop.
  • Ignoring compiler error messages.

Best Practices

  • Prefer message passing over shared memory.
  • Use Arc<Mutex<T>> for shared mutable data.
  • Keep locks short.
  • Always join threads.
  • Handle all IO errors with Result.
  • Use ? to propagate errors.
  • Document why you use unsafe.
  • Test concurrent code carefully.
  • Use cargo clippy.
  • Read the Rust concurrency documentation.

Illustrations and Diagrams

Threads Running at the Same Time

  Main Thread
      |
      +--> Worker Thread 1 ---> Task A
      |
      +--> Worker Thread 2 ---> Task B
      |
      +--> Worker Thread 3 ---> Task C
      |
      V
  Join all threads
      |
      V
  Program ends
  

Channel Communication

  Thread 1 (Sender)
      |
      V
  [ Channel ]
      |
      V
  Thread 2 (Receiver)
  

Mutex Locking

  Thread 1 ---> lock() ---> Use data ---> unlock()
  Thread 2 ---> wait...          |
                                 V
                          (when unlocked)
                                 |
                                 V
  Thread 2 ---> lock() ---> Use data ---> unlock()
  

Arc + Mutex Sharing

  Arc>
        |
        +--> Thread 1: lock, change, unlock
        |
        +--> Thread 2: lock, change, unlock
        |
        +--> Thread 3: lock, change, unlock
        |
        V
  Final value
  

File Read/Write

  Program
     |
     +--> fs::File::create("file.txt")
     |         |
     |         V
     |    writeln!(file, "data")
     |
     +--> fs::read_to_string("file.txt")
               |
               V
          Ok(content) or Err(e)
  

Your Learning Journey

  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 🎉
  

Comparison Tables

Threads vs Channels vs Mutex

FeatureThreadsChannelsMutex
PurposeRun code in parallelSend messagesLock shared data
SafetySafe with ownershipVery safeSafe with care
Use caseParallel tasksCommunicationShared state

Mutex vs Arc

FeatureMutexArc
PurposeLock dataShare ownership
Used withThreadsThreads
TogetherArc<Mutex<T>> for shared mutable data

File Read vs Write

OperationFunctionReturns
Readfs::read_to_stringResult<String>
Writefs::writeResult<()>
Createfs::File::createResult<File>

Safe vs Unsafe Rust

FeatureSafe RustUnsafe Rust
Memory safetyGuaranteedYou must ensure
Use caseMost programsHardware, FFI
KeywordDefaultunsafe { }

Lesson Summaries

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.

End-of-Module Summary

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!

Frequently Asked Questions

  1. What is concurrency? Doing many tasks at the same time.
  2. What is a thread? A worker inside your program.
  3. What is a channel? A safe way for threads to send messages.
  4. What is a Mutex? A lock that allows only one thread to access data at a time.
  5. What is Arc? A smart pointer for shared ownership across threads.
  6. How do I read a file? Use fs::read_to_string.
  7. How do I get command-line arguments? Use env::args().
  8. How do I read environment variables? Use env::var().
  9. What is unsafe? A keyword that lets you do dangerous things carefully.
  10. What is async? Doing slow tasks without blocking others.

Matching Exercises

Match the word to its definition.

WordDefinition
1. ThreadA. Safe message sending.
2. ChannelB. Lock for shared data.
3. MutexC. Worker in a program.
4. ArcD. Stored data on disk.
5. FileE. Shared ownership.

Answers: 1-C, 2-A, 3-B, 4-E, 5-D

Scenario-based Exercises

  1. Scenario: You want to process 10 files at the same time. What do you use?
    Answer: Threads.
  2. Scenario: Two threads need to add to the same counter. What do you use?
    Answer: Arc<Mutex<i32>>.
  3. Scenario: A thread needs to send a result to the main thread. What do you use?
    Answer: A channel.
  4. Scenario: You want to read a file and print its contents. What do you use?
    Answer: fs::read_to_string.
  5. Scenario: You want your program to accept a filename from the user. What do you use?
    Answer: env::args().

Group Activity

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.

Individual Activity

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().

Mini Project

Project: “My File Logger”

Write a Rust program that:

  1. Creates a file called log.txt.
  2. Writes a message to the file every time it runs.
  3. Reads the file and prints all previous messages.
  4. Uses Result and ? to handle errors.

Example output:

  Log started at 10:00
  Log started at 10:05
  Log started at 10:12
  

Practical Assignment

Assignment: Create a new Cargo project called file_stats. In main.rs, write a program that:

  1. Reads file names from command-line arguments.
  2. For each file, spawns a thread that reads the file and counts lines and words.
  3. Sends the results back through a channel.
  4. Prints the results in the main thread.
  5. Handles missing files gracefully with Result.

Submit: Your main.rs file and a screenshot of the program running.

Key Takeaways

  • Concurrency means doing many tasks at once.
  • Threads are workers in your program.
  • Channels send messages safely.
  • Mutex locks shared data.
  • Arc shares ownership.
  • Files store data with std::fs.
  • Arguments come from env::args().
  • Environment variables come from env::var().
  • Command-line tools automate tasks.
  • Use unsafe only when necessary.
  • Always handle errors with Result.

Classroom Discussion Questions

  1. Why is concurrency important in modern programs?
  2. What is the difference between a thread and a process?
  3. Why are channels safer than shared memory?
  4. Why does Rust have Mutex and Arc?
  5. What could happen if two threads write to the same file at once?
  6. Why are command-line tools useful?
  7. When should you use unsafe?
  8. What is the difference between sync and async code?
  9. How do you debug a concurrent program?
  10. What did Ada learn from the busy market stall story?

Preparation for Module Six

In Module Six, we will finish the course. We will learn about:

  • Project structure and workspaces.
  • Publishing crates to crates.io.
  • Documentation with rustdoc.
  • Benchmarking and performance tuning.
  • Code review and style guidelines.
  • Security best practices.
  • Capstone project: build a complete Rust application.
  • Exam preparation and practice questions.

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

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→