parking_lot for Rust: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

parking_lot for Rust: Fast Synchronization Primitives

\n\n

The parking_lot library is one of the most popular and performant implementations of synchronization primitives for the Rust language. It provides an alternative to standard mutexes (std::sync::Mutex), read-write locks (std::sync::RwLock), and condition variables (std::sync::Condvar), but with significantly better performance and smaller code size.

\n\n

Why is this library needed? Standard synchronization primitives in Rust, while safe, have several drawbacks: they use system calls (futex on Linux) even in simple scenarios, require additional memory for flags, and have a more complex internal implementation. parking_lot solves these problems by using more efficient algorithms (e.g., optimistic locks and spin-loops) and minimizing overhead. As a result, code runs faster, especially in multi-threaded applications with high contention.

\n\n

The library is fully compatible with Rust and does not require unsafe code on the user's side. It offers the same interfaces as the standard library, but with additional features: Mutex with timeout support, RwLock with a fair queue, Once for lazy initialization, and ReentrantMutex for reentrant locks. parking_lot is the de facto standard for high-performance Rust applications, from web servers to game engines.

\n\n

Installation

\n\n

Add the library to your project's Cargo.toml file:

\n\n
[dependencies]\nparking_lot = "0.12"
\n\n

Then run the command:

\n\n
cargo build
\n\n

Or, if you use cargo add (starting from Rust 1.62):

\n\n
cargo add parking_lot
\n\n

After that, you can import primitives from the library:

\n\n
use parking_lot::{Mutex, RwLock, Condvar, Once, ReentrantMutex};
\n\n

Quick Start: Minimal Working Example

\n\n

Here is a simple example of using Mutex from parking_lot to protect a shared counter in a multi-threaded environment:

\n\n
use parking_lot::Mutex;\nuse std::thread;\n\nfn main() {\n    // Create a mutex wrapping the value\n    let counter = Mutex::new(0);\n\n    // Create 10 threads, each increments the counter by 1\n    let mut handles = vec![];\n    for _ in 0..10 {\n        let handle = thread::spawn(|| {\n            // Acquire the lock — .lock() returns an RAII guard\n            let mut guard = counter.lock();\n            *guard += 1;\n            // guard is automatically released when it goes out of scope\n        });\n        handles.push(handle);\n    }\n\n    // Wait for all threads to finish\n    for handle in handles {\n        handle.join().unwrap();\n    }\n\n    // Read the final value\n    let final_value = *counter.lock();\n    println!("Final value: {}", final_value); // Should be 10\n}
\n\n

In this example, counter.lock() returns a MutexGuard, which automatically releases the lock upon destruction. Unlike the standard std::sync::Mutex, there is no need to handle errors (poisoning) — parking_lot does not poison the mutex on panic by default.

\n\n

Main Methods and Types

\n\n

Below are 8 key methods/types of the parking_lot library with signatures, descriptions, and examples.

\n\n

1. Mutex::lock()

\n

Signature: pub fn lock(&self) -> MutexGuard<'_, T>

\n

Description: Acquires the mutex, blocking the current thread until the lock is obtained. Returns an RAII guard that automatically releases the lock upon exit

Recommendations