Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Mutex<T> / RwLock<T>

Mutex<T> / RwLock<T>

To safely share and modify data across multiple threads, use Rust's Mutex<T> or RwLock<T>. Both are combined with Arc<T> to share ownership across threads.

Syntax

use std::sync::{Arc, Mutex, RwLock};

// Mutex — exclusive lock (only one thread can write at a time)
let mutex = Arc::new(Mutex::new(0i32));
let m = Arc::clone(&mutex);
let mut val = m.lock().unwrap();  // Acquires the lock (other threads will block).
*val += 1;                         // Modifies the value while holding the lock.
// The lock is automatically released when val goes out of scope.

// RwLock — read lock (multiple readers allowed / writes are exclusive)
let rwlock = Arc::new(RwLock::new(vec![1, 2, 3]));
let r = rwlock.read().unwrap();    // Multiple threads can read simultaneously.
let mut w = rwlock.write().unwrap(); // Blocks other threads when writing.

Method List

MethodDescription
Mutex::new(val)Creates a new Mutex wrapping the given value.
mutex.lock()Acquires the lock. Returns Result<MutexGuard>. Blocks if another thread holds the lock.
mutex.try_lock()Attempts to acquire the lock immediately. Returns Err if the lock is unavailable (non-blocking).
MutexGuard (guard)Automatically releases the lock when it goes out of scope (RAII).
RwLock::new(val)Creates a new RwLock wrapping the given value.
rwlock.read()Acquires a read lock. Multiple threads can hold read locks simultaneously.
rwlock.write()Acquires a write lock. Blocks until all read and write locks are released.
Arc::new(val)Creates a thread-safe reference-counted pointer. Used together with Mutex or RwLock.
Arc::clone(&arc)Clones the pointer by incrementing the reference count. Used to share ownership across threads.

Sample Code

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

fn main() {
    // --- Basic Mutex usage ---
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    // 10 threads increment the counter concurrently.
    for _ in 0..10 {
        let c = Arc::clone(&counter);
        let h = thread::spawn(move || {
            let mut val = c.lock().unwrap();  // Acquires the lock.
            *val += 1;
            // The lock is released when val goes out of scope.
        });
        handles.push(h);
    }

    for h in handles {
        h.join().unwrap();
    }
    println!("Counter: {}", *counter.lock().unwrap());  // 10

    // --- Release the lock early to avoid deadlocks ---
    let data = Arc::new(Mutex::new(vec![1, 2, 3]));
    {
        let mut guard = data.lock().unwrap();
        guard.push(4);
    }  // guard is dropped here and the lock is released.
    println!("data: {:?}", *data.lock().unwrap());  // [1, 2, 3, 4]

    // --- RwLock — useful when reads are frequent ---
    let config = Arc::new(RwLock::new(String::from("initial")));
    let mut handles = vec![];

    // Multiple reader threads
    for i in 0..3 {
        let c = Arc::clone(&config);
        let h = thread::spawn(move || {
            let val = c.read().unwrap();  // Multiple threads can read at the same time.
            println!("Reader thread {}: {}", i, *val);
        });
        handles.push(h);
    }

    // Writer thread (runs after all read locks are released)
    {
        let c = Arc::clone(&config);
        let h = thread::spawn(move || {
            let mut val = c.write().unwrap();
            *val = String::from("updated");
            println!("Write complete");
        });
        handles.push(h);
    }

    for h in handles {
        h.join().unwrap();
    }
    println!("Final value: {}", *config.read().unwrap());  // updated
}

Overview

Mutex is an exclusive lock that allows only one thread to access the data at a time. You acquire the lock with lock(), and the returned MutexGuard automatically releases the lock when it goes out of scope (RAII).

RwLock allows multiple threads to read simultaneously, but writes are exclusive. It is more efficient than Mutex when reads are frequent and writes are rare.

Deadlock warning: If the same thread tries to acquire the same Mutex lock twice, it will deadlock. Keep lock scopes as short as possible, and avoid acquiring another lock while already holding one. For thread basics, see std::thread::spawn() / join(). For channels, see std::sync::mpsc channel.

If you find any errors or copyright issues, please .