Crate spinlock [] [src]

This crate provides a thread-safe data container.

Description

This structure behaves a lot like a normal Mutex. There are some differences:

  • It may be used outside the runtime.
    • A normal mutex will fail when used without the runtime, this will just lock
    • When the runtime is present, it will call the deschedule function when appropriate
  • No lock poisoning. When a fail occurs when the lock is held, no guarantees are made

When calling rust functions from bare threads, such as C pthreads, this lock will be very helpfull. In other cases however, you are encouraged to use the locks from the standard library.

Simple example

use spinlock::Spinlock;
let spinlock = Spinlock::new(0);

// Modify the data
{
    let mut data = spinlock.lock();
    *data = 2;
}

// Read the data
let answer =
{
    let data = spinlock.lock();
    *data
};

assert_eq!(answer, 2);

Thread-safety example

use spinlock::Spinlock;
use std::sync::{Arc, Barrier};

let numthreads = 1000;
let spinlock = Arc::new(Spinlock::new(0));

// We use a barrier to ensure the readout happens after all writing
let barrier = Arc::new(Barrier::new(numthreads + 1));

for _ in (0..numthreads)
{
    let my_barrier = barrier.clone();
    let my_lock = spinlock.clone();
    std::thread::spawn(move||
    {
        let mut guard = my_lock.lock();
        *guard += 1;

        // Release the lock to prevent a deadlock
        drop(guard);
        my_barrier.wait();
    });
}

barrier.wait();

let answer = { *spinlock.lock() };
assert_eq!(answer, numthreads);

Structs

Spinlock

A wrapper for the data giving access in a thread-safe manner

SpinlockGuard

A guard to which the protected data can be accessed

Constants

INIT_STATIC_SPINLOCK
STATIC_SPINLOCK_INIT

A initializer for StaticSpinlock, containing no data.

Type Definitions

StaticSpinlock

A Spinlock which may be used statically.