mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-26 00:00:16 +02:00
sync: Add LockFuture for Lock (#1184)
This commit is contained in:
committed by
Carl Lerche
parent
448302c3d4
commit
e2b4bdb647
@@ -44,7 +44,9 @@ use crate::semaphore;
|
||||
|
||||
use std::cell::UnsafeCell;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::Poll::Ready;
|
||||
use std::task::{Context, Poll};
|
||||
@@ -71,6 +73,12 @@ pub struct Lock<T> {
|
||||
#[derive(Debug)]
|
||||
pub struct LockGuard<T>(Lock<T>);
|
||||
|
||||
/// A future that resolves to a `LockGuard`.
|
||||
#[derive(Debug)]
|
||||
pub struct LockFuture<'a, T> {
|
||||
lock: &'a mut Lock<T>,
|
||||
}
|
||||
|
||||
// As long as T: Send, it's fine to send and share Lock<T> between threads.
|
||||
// If T was not Send, sending and sharing a Lock<T> would be bad, since you can access T through
|
||||
// Lock<T>.
|
||||
@@ -120,6 +128,11 @@ impl<T> Lock<T> {
|
||||
};
|
||||
Ready(LockGuard(acquired))
|
||||
}
|
||||
|
||||
/// A future that resolves on acquiring the lock and returns the `LockGuard`.
|
||||
pub fn lock(&mut self) -> LockFuture<'_, T> {
|
||||
LockFuture { lock: self }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for LockGuard<T> {
|
||||
@@ -179,3 +192,12 @@ impl<T: fmt::Display> fmt::Display for LockGuard<T> {
|
||||
fmt::Display::fmt(&**self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Future for LockFuture<'_, T> {
|
||||
type Output = LockGuard<T>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let me = &mut *self;
|
||||
Pin::new(&mut *me.lock).poll_lock(cx)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user