Skip to content

Instantly share code, notes, and snippets.

@avnerbarr
Created November 4, 2020 07:19
Show Gist options
  • Save avnerbarr/e0b356e5db4b988f5482a4f442ab6dba to your computer and use it in GitHub Desktop.
Save avnerbarr/e0b356e5db4b988f5482a4f442ab6dba to your computer and use it in GitHub Desktop.
// lock code around a file handle when multiple processes running and single access
fn main() {
std::thread::spawn(|| {
let lock = with_lock("my_lock".to_string());
loop {
let r = lock(|| {
sleep(Duration::from_millis(100));
"blah"
});
sleep(Duration::from_millis(500));
println!("{:?}",r);
}
});
let lock = with_lock("my_lock".to_string());
loop {
let now = std::time::Instant::now();
let r = lock(|| {
sleep(Duration::from_millis(100));
"blah2"
});
sleep(Duration::from_millis(100));
println!("{:?}",r);
}
}
#[derive(Debug)]
enum LockResult<T> {
Some(T),
Locked
}
extern crate fs2;
use fs2::FileExt;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
use std::thread::sleep;
use std::time::Duration;
use std::path::PathBuf;
use std::io::Error;
fn with_lock<T, F>(name: String) -> impl Fn(F) -> LockResult<T> where F: Fn() -> T {
move |block| {
let mut pb = std::env::temp_dir();
pb.push(&name);
// println!("lock file is at {:?}",&pb);
let lock_file = File::create(&pb);
match lock_file {
Ok(lock_file) => {
let lock = lock_file.try_lock_exclusive();
if lock.is_err() {
return LockResult::Locked;
}
let r= block();
lock_file.unlock();
LockResult::Some(r)
}
Err(_) => {
return LockResult::Locked;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment