9 releases (breaking)

Uses old Rust 2015

0.7.0 Dec 30, 2018
0.6.0 Apr 10, 2018
0.5.1 Nov 3, 2017
0.5.0 Aug 6, 2016
0.2.1 Jun 23, 2015

#1150 in Concurrency

44 downloads per month
Used in xan

GPL-2.0+

28KB
323 lines

namedlock

Documentation


lib.rs:

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 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();
	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.

Dependencies

~0–3MB
~52K SLoC