Crate namedlock [] [src]

Namespaces for named locks.

This is useful when synchronizing access to a named resource, but you only know the name of the resource at runtime.

For example, you can use this to synchronize access to the filesystem:

use std::thread;
use std::env;
use std::fs::{OpenOptions,File};
use std::path::PathBuf;
use std::ffi::OsString;
use std::io::{Read,Seek,Write,SeekFrom};
use std::str::FromStr;
use std::sync::Arc;
use namedlock::{LockSpace,AutoCleanup};

// Short-hand function for space.with_lock that opens the file if necessary
fn with_file<R,F>(space:LockSpace<OsString,File>,filename:Arc<PathBuf>,f: F) -> R
    where F: FnOnce(&mut File) -> R
{
    space.with_lock(filename.as_os_str().to_owned(),
        ||OpenOptions::new().read(true).write(true).open(&*filename).unwrap(),f
    ).unwrap()
}

// Initialize the file
let mut filename=env::temp_dir();
filename.push("namedlock-test");
let filename=Arc::new(filename);
File::create(&*filename).unwrap().write_all(b"0").unwrap();

let space=LockSpace::<OsString,File>::new(AutoCleanup);
let mut threads=vec![];

// Have 1000 threads increment the value in the file, one at a time
for i in 0..1000 {
    let space_clone=space.clone();
    let filename_clone=filename.clone();
    threads.push(thread::Builder::new().name(format!("{}",i))
        .spawn(move||with_file(space_clone,filename_clone,|file| {
            let mut buf=String::new();
            file.seek(SeekFrom::Start(0)).unwrap();
            file.read_to_string(&mut buf).unwrap();
            file.seek(SeekFrom::Start(0)).unwrap();
            write!(file,"{}",usize::from_str(&buf).unwrap()+1).unwrap();
        })).unwrap()
    );
}

// Wait until all threads are done
let count=threads.len();
for t in threads.into_iter() {
    t.join().unwrap();
}

// Check the result
with_file(space,filename,|file| {
    let mut buf=String::new();
    file.seek(SeekFrom::Start(0)).unwrap();
    file.read_to_string(&mut buf).unwrap();
    assert_eq!(count,usize::from_str(&buf).unwrap());
});

License

namedlock - Copyright (C) 2015 Jethro G. Beekman

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

Reexports

pub use Cleanup::KeepUnused;
pub use Cleanup::AutoCleanup;

Modules

lockresult

A Result type very similar to std::sync::LockResult.

ownedmutexguard

Mutex guards that own the Mutex.

Structs

LockSpace

A LockSpace<K,V> holds many Mutex<V>'s, keyed by K.

LockSpaceGuard

An RAII implementation of a "scoped lock" of a a LockSpace value. When this structure is dropped (falls out of scope), the lock will be unlocked, and the reference count to the key will be decreased by 1.

Enums

Cleanup
LockSpaceRemoveResult