Build, unsafe, FFI and threads · 13 min · free lesson

pthreads to std::thread

Rust threads are the same OS threads as pthreads, but a Mutex owns the data it protects and the compiler rejects data races.

Core idea

thread::spawn needs a Send + 'static closure, so captures are moved in; shared state goes in Arc<Mutex<T>>, and the lock guard unlocks when it drops.

C and Rust, side by side

C hits is shared without a lock, which ThreadSanitizer reports as a data race; safe_hits is protected only by convention.
#include <pthread.h>
#include <stdio.h>

static long hits = 0;                       /* shared and unprotected */
static long safe_hits = 0;                  /* protected by `lock`, by convention */
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

static void *work(void *arg) {
    (void)arg;
    for (int i = 0; i < 100000; i++) {
        hits++;                             /* data race: TSan reports it */
        pthread_mutex_lock(&lock);
        safe_hits++;
        pthread_mutex_unlock(&lock);        /* an early return here would deadlock */
    }
    return NULL;
}

int main(void) {
    pthread_t t[4];
    for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, work, NULL);
    for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
    printf("safe_hits=%ld (hits=%ld may be lower)\n", safe_hits, hits);
    return 0;
}
Rust Each thread owns a clone of the Arc, the counter lives inside the Mutex, and each guard unlocks at the end of its statement.
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let hits = Arc::new(Mutex::new(0u64)); // the Mutex owns the counter
    let mut handles = Vec::new();
    for _ in 0..4 {
        let hits = Arc::clone(&hits);       // one shared owner per thread
        handles.push(thread::spawn(move || { // `move`: the thread owns its Arc
            for _ in 0..100_000 {
                *hits.lock().unwrap() += 1; // the guard drops at `;`: unlocked
            }
        }));
    }
    for handle in handles {
        handle.join().unwrap();
    }
    println!("hits={}", *hits.lock().unwrap());
}
What changes
CRust
A mutex protects data by convention.Mutex<T> owns the T; the data is reachable only through lock().
pthread_mutex_unlock must run on every path.The guard unlocks when it drops, including on early returns.
Passing &local to a thread compiles and may dangle.spawn needs 'static; borrowing a local is E0373, so use move or thread::scope.

Understand it

With pthreads, the relationship between a mutex and the data it protects is a convention: lock guards safe_hits because everyone agrees to lock first. Nothing stops the unprotected hits++, which ThreadSanitizer reports as a data race, and forgetting pthread_mutex_unlock on one early return deadlocks the next thread that locks.

std::thread::spawn starts an OS thread and returns a JoinHandle; join() waits for it and returns the thread's result. The closure must be 'static, because the thread may outlive the function that spawned it, so borrowing a local is rejected with E0373, closure may outlive the current function. move makes the closure own its captures instead. When threads only need to borrow locals for a bounded time, thread::scope guarantees they are joined before the scope ends and lets them borrow.

Mutex<T> contains the T. The only way to reach the value is lock(), which returns a guard that dereferences to the data and unlocks when it is dropped, at the end of its statement or block, including on an early return or a panic. Arc<T> is an atomically reference-counted pointer, so each thread can own a handle to the same mutex; the non-atomic Rc<T> is not Send, and the compiler refuses to move it into a thread.

Those checks come from two marker traits. Send means a value can be moved to another thread, and Sync means &T can be shared between threads. Types implement them automatically when all their fields do, which is how the compiler proves a safe program free of data races. Deadlocks and lock ordering remain your design problem, as in C.

The C habit, written in Rust

This is how the C version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

use std::thread;

fn main() {
    let mut hits = 0u64;
    let handle = thread::spawn(|| {
        hits += 1;
    });
    handle.join().unwrap();
    println!("{hits}");
}

Practise this code in Playground ↗

Try it

Explain where the quiz program unlocks its mutex and why the closure needs move, then fix the practice program with an Arc<Mutex<u64>>.

What success looks like: You can point to the statement where each guard drops and explain why a spawned thread cannot borrow a local of main.

Check your understanding

In let total = Arc::clone(&total); thread::spawn(move || { let mut n = total.lock().unwrap(); *n += 1; });, where is the mutex unlocked, and why is move needed?

Reveal the answer
  1. At join(); move is optional because Arc is thread-safe
  2. Only when drop(total) is called; move copies the counter into the thread
  3. After the loop that spawns the threads; move makes the closure Copy
  4. When the guard n drops at the end of the closure; move gives the thread its own Arc, because the thread may outlive the locals of the function that spawned it

The guard is a local of the closure and unlocks when it goes out of scope. Without move, the closure would borrow total, and spawn requires 'static captures.

Go deeper

Common misconception: “A Rust Mutex is a separate lock object, like a pthread_mutex_t next to the data.”

Mutex<T> wraps the data itself. Code that does not hold a guard has no path to the T, so forgetting to lock does not compile, and the guard makes forgetting to unlock impossible.

  1. Find the shared data: List what the C threads share, and put each item inside the Mutex or atomic that protects it.
  2. Give each thread an owner: Clone the Arc once per thread and move the clone into that thread's closure.
  3. Locate the unlock: Find where each guard is dropped; keep guards out of slow operations, and never take two locks in different orders.

Transfer challenge: Replace Mutex<u64> with AtomicU64 and fetch_add(1, Ordering::Relaxed), then explain why Relaxed is enough for a counter that is read only after every join.

Connections

  • unsafe, Raw Pointers and FFI: Where Rust hands the proof back to you
Side-by-side comparison: the C version on the left, the Rust version on the right, then 3 rows naming what changes.
pthreads to std::thread: the same task in C and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: pthreads to std::thread (courseId "rust-for-c-developers", lessonId "c-pthreads-to-threads")
Link: https://crabrix.com/learn/rust-for-c-developers/c-pthreads-to-threads/
Goal: thread::spawn needs a Send + 'static closure, so captures are moved in; shared state goes in Arc<Mutex<T>>, and the lock guard unlocks when it drops.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-pthreads-to-threads) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.