I want to prevent concurrent execution of a function called asynchronously.
The function gets called from a hyper service and two connections should lead to one waiting until the other function call is done. I thought implementing a Future to block execution until other threads / connections are done will solve the issue. Coming to my problem I store the Futures in a Mutex<HashMap<i64, LockFut>> but when I lock the mutex to get and await the LockFut it obviously complains about the MutexGuard not being send. I don't know how to work around this or if my way is just bad.
|
132 | let mut locks = LOCKS.lock().unwrap();
| --------- has type `std::sync::MutexGuard<'_, std::collections::HashMap<i64, hoster::hoster::LockFut>>`
...
136 | lock.await;
| ^^^^^^^^^^ await occurs here, with `mut locks` maybe used later
137 | }
| - `mut locks` is later dropped here
This is my future implementation
lazy_static! {
static ref LOCKS: Mutex<HashMap<i64, LockFut>> = Mutex::new(HashMap::new());
}
struct LockState {
waker: Option<Waker>,
locked: bool
}
struct LockFut {
state: Arc<Mutex<LockState>>
}
impl Future for LockFut {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = self.state.lock().unwrap();
match state.locked {
false => {
Poll::Ready(())
},
true => {
state.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
}
impl LockFut {
fn new() -> LockFut {
LockFut {
state: Arc::new(Mutex::new(LockState {
locked: false,
waker: None
}))
}
}
pub fn release_lock(&mut self) {
let mut state = self.state.lock().unwrap();
state.locked = false;
if let Some(waker) = state.waker.take() {
waker.wake();
}
}
pub async fn lock<'a>(id: i64) {
let mut locks = LOCKS.lock().unwrap();
// Wait for existing lock to be unlocked or create a new lock
let lock = locks.entry(id).or_insert(LockFut::new());
// Wait for the potential lock to be released
lock.await;
}
pub fn unlock(id: i64) {
match LOCKS.lock().unwrap().get_mut(&id) {
Some(lock) => lock.release_lock(),
None => warn!("No lock found for: {}", id)
};
}
}
And this is how I call it
async fn is_concurrent(id: i64) {
should_not_be_concurrent().await;
}
async fn should_not_be_concurrent(id: i64) {
LockFut::lock(id).await;
// Do crazy stuff
LockFut::unlock(id);
}