Rust Threads Examples

Rust Threads Example

In this tutorial we aim to learn about threads by looking at various simple easy to understand examples.

Example 1: Rust Threads

A beginner friendly Rust threading example.

Step 1: Dependencies

No third party crate is needed.

Step 2: Write Code

Here is the full code.

use std::sync::{Arc, Mutex};
use std::sync::mpsc;
use std::thread;

fn generate_task_number() -> isize {
fn main() {
    // Print something profound in a different task using a named function
    fn print_message() { println!("I am running in a different task!"); }

    // Print something more profound in a different task using a lambda expression
    thread::spawn(|| { println!("I am also running in a different task!") });

    // It returns a handle to the thread, that can be used to wait for the child thread to finish and extract its result:
    let handle = thread::spawn(|| {
        "Hello from a thread!"
    let result = handle.join();
    println!("{}", result.unwrap());

    // Generate some state locally
    let child_task_number_10 = generate_task_number();

    // to force the closure to take ownership of child_task_number (and any other referenced
    // variables), use the move keyword
    thread::spawn(move || {
           // Capture it in the remote task
           println!("I am child number {}", child_task_number_10);

    for child_task_number in 0u32..20 {
        thread::spawn(move || {
            print!("I am child number {}\n", child_task_number);

    let data = Arc::new(Mutex::new(0));
    let (tx, rx) = mpsc::channel();

    for _ in 0..10 {
        let (data, tx) = (data.clone(), tx.clone());
        thread::spawn(move || {
            // lock(), which acquires the mutex's lock.
            let mut data = data.lock().unwrap();
            *data += 1;
            let _unused = tx.send(*data);
    for _ in 0..10 {
        println!("{}", rx.recv().unwrap());

Step 3: Run

  1. Copy the above code.
  2. Run

You will get the following:

I am running in a different task!
Hello from a thread!
I am also running in a different task!
I am child number 13
I am child number 15

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *