Crate namedlock

source ·
Expand description

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

// Initialize the file
let mut filename=env::temp_dir();
let filename=Arc::new(filename);

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

// Have 10 threads increment the value in the file, one at a time
for i in 0..10 {
	let space_clone=space.clone();
	let filename_clone=filename.clone();
		.spawn(move||with_file(space_clone,filename_clone,|file| {
			let mut buf=String::new();;
			file.read_to_string(&mut buf).unwrap();;

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

// Check the result
with_file(space,filename,|file| {
	let mut buf=String::new();;
	file.read_to_string(&mut buf).unwrap();


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.


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


A Result type very similar to std::sync::LockResult.
Mutex guards that own the Mutex.


A LockSpace<K,V> holds many Mutex<V>’s, keyed by K.
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.