#locking #thread #performance #take-lock

take_lock

a dead simple lock around Option<Box<T>> thats similar in spirit to OnceLock but adds a bit more flexibility by paying a bit in performance

3 releases

Uses new Rust 2024

new 0.1.11 May 7, 2025
0.1.1 May 7, 2025
0.1.0 May 7, 2025

#499 in Concurrency

MIT/Apache

12KB
216 lines

take_lock

TakeLock is a minimal, thread-safe container for passing ownership of a single Box<T> between threads.

It provides an atomic, lock-free way to put, take, or swap a value across threads. This is implemented with a fairly straight forward use of atomics.

Example

use take_lock::TakeLock;
use std::thread;

let lock = std::sync::Arc::new(TakeLock::default());

let sender = {
    let lock = lock.clone();
    thread::spawn(move || {
        lock.put(Some(Box::new(123))).unwrap();
    })
};

let receiver = {
    let lock = lock.clone();
    thread::spawn(move || {
        loop {
            if let Some(val) = lock.take() {
                assert_eq!(*val, 123);
                break;
            }
        }
    })
};

sender.join().unwrap();
receiver.join().unwrap();

No runtime deps