1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
use std::hash::Hash;
use super::limit::{AsyncLimit, SyncLimit};
use super::lockable_hash_map::LockableHashMap;
use super::lockable_trait::Lockable;
use super::utils::never::InfallibleUnwrap;
/// A pool of locks where individual locks can be locked/unlocked by key.
/// It initially considers all keys as "unlocked", but they can be locked
/// and if a second thread tries to acquire a lock for the same key, they will have to wait.
///
/// ```
/// use lockable::LockPool;
///
/// let pool = LockPool::new();
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let guard1 = pool.async_lock(4).await;
/// let guard2 = pool.async_lock(5).await;
///
/// // This next line would cause a deadlock or panic because `4` is already locked on this thread
/// // let guard3 = pool.async_lock(4).await;
///
/// // After dropping the corresponding guard, we can lock it again
/// std::mem::drop(guard1);
/// let guard3 = pool.async_lock(4).await;
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
///
/// You can use an arbitrary type to index locks by, as long as that type implements [PartialEq] + [Eq] + [Hash] + [Clone] + [Debug].
///
/// ```
/// use lockable::LockPool;
///
/// #[derive(PartialEq, Eq, Hash, Clone, Debug)]
/// struct CustomLockKey(u32);
///
/// let pool = LockPool::new();
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let guard = pool.async_lock(CustomLockKey(4)).await;
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
///
/// Under the hood, a [LockPool] is a [LockPool] with `()` as a value type, i.e. `LockPool<K>` is just a wrapper
/// around `LockPool<K, ()>` with a simpler API. If you need more complex functionalities, please look at
/// [LockPool].
pub struct LockPool<K>
where
K: Eq + PartialEq + Hash + Clone,
{
map: LockableHashMap<K, ()>,
}
impl<K> Lockable<K, ()> for LockPool<K>
where
K: Eq + PartialEq + Hash + Clone,
{
type Guard<'a> = <LockableHashMap<K, ()> as Lockable<K, ()>>::Guard<'a>
where
K: 'a;
type OwnedGuard = <LockableHashMap<K, ()> as Lockable<K, ()>>::OwnedGuard;
}
impl<K> LockPool<K>
where
K: Eq + PartialEq + Hash + Clone,
{
/// Create a new lock pool with no locked keys.
///
/// Examples
/// -----
/// ```
/// use lockable::LockPool;
///
/// let pool = LockPool::new();
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let guard = pool.async_lock(4).await;
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
#[inline]
pub fn new() -> Self {
Self {
map: LockableHashMap::new(),
}
}
/// Return the number of locked keys in the pool.
///
/// Examples
/// -----
/// ```
/// use lockable::LockPool;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let pool = LockPool::new();
///
/// // Lock two entries
/// let guard1 = pool
/// .async_lock(4)
/// .await;
/// let guard2 = pool
/// .async_lock(5)
/// .await;
///
/// // Now we have two locked entries
/// assert_eq!(2, pool.num_locked());
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
#[inline]
pub fn num_locked(&self) -> usize {
self.map.num_entries_or_locked()
}
/// Lock a key and return a guard for it.
///
/// Locking a key prevents any other threads from locking the same key.
/// If the lock with this key is currently locked by a different thread, then the current thread blocks until it becomes available.
/// Upon returning, the thread is the only thread with the lock held. A RAII guard is returned to allow scoped unlock
/// of the lock. When the guard goes out of scope, the lock will be unlocked.
///
/// This function can only be used from non-async contexts and will panic if used from async contexts.
///
/// The exact behavior on locking a lock in the thread which already holds the lock is left unspecified.
/// However, this function will not return on the second call (it might panic or deadlock, for example).
///
/// Panics
/// -----
/// - This function might panic when called if the lock is already held by the current thread.
/// - This function will also panic when called from an `async` context.
/// See documentation of [tokio::sync::Mutex] for details.
///
/// Examples
/// -----
/// ```
/// use lockable::LockPool;
///
/// # (|| {
/// let pool = LockPool::new();
/// let guard1 = pool.blocking_lock(4);
/// let guard2 = pool.blocking_lock(5);
///
/// // This next line would cause a deadlock or panic because `4` is already locked on this thread
/// // let guard3 = pool.blocking_lock(4);
///
/// // After dropping the corresponding guard, we can lock it again
/// std::mem::drop(guard1);
/// let guard3 = pool.blocking_lock(4);
/// # Ok::<(), lockable::Never>(())})().unwrap();
/// ```
#[inline]
pub fn blocking_lock(&self, key: K) -> <Self as Lockable<K, ()>>::Guard<'_> {
self.map
.blocking_lock(key, SyncLimit::no_limit())
.infallible_unwrap()
}
// TOOD Add this
// /// Lock a key and return a guard for it.
// ///
// /// This is identical to [LockPool::blocking_lock], please see documentation for that function for more information.
// /// But different to [LockPool::blocking_lock], [LockPool::blocking_lock_owned] works on an `Arc<LockPool>`
// /// instead of a [LockPool] and returns a [Lockable::OwnedGuard] that binds its lifetime to the [LockPool] in that [Arc].
// /// Such a [Lockable::OwnedGuard] can be more easily moved around or cloned than the [Lockable::Guard] returned by [LockPool::blocking_lock].
// ///
// /// Examples
// /// -----
// /// ```
// /// use lockable::LockPool;
// /// use std::sync::Arc;
// ///
// /// # (|| {
// /// let pool = Arc::new(LockPool::new());
// /// let guard1 = pool.blocking_lock_owned(4);
// /// let guard2 = pool.blocking_lock_owned(5);
// ///
// /// // This next line would cause a deadlock or panic because `4` is already locked on this thread
// /// // let guard3 = pool.blocking_lock_owned(4);
// ///
// /// // After dropping the corresponding guard, we can lock it again
// /// std::mem::drop(guard1);
// /// let guard3 = pool.blocking_lock_owned(4);
// /// # Ok::<(), lockable::Never>(())})().unwrap();
// /// ```
// #[inline]
// pub fn blocking_lock_owned(self: &Arc<Self>, key: K) -> <Self as Lockable<K, ()>>::OwnedGuard {
// self.map
// .blocking_lock_owned(key, SyncLimit::no_limit())
// .infallible_unwrap()
// }
/// Attempts to acquire the lock with the given key.
/// Any changes to that entry will be persisted in the map.
/// Locking a key prevents any other threads from locking the same key, but the action of locking a key doesn't insert
/// a map entry by itself. Map entries can be inserted and removed using [Guard::insert] and [Guard::remove] on the returned entry guard.
///
/// If the lock could not be acquired because it is already locked, then [Ok](Ok)([None]) is returned. Otherwise, a RAII guard is returned.
/// The lock will be unlocked when the guard is dropped.
///
/// This function does not block and can be used from both async and non-async contexts.
///
/// Examples
/// -----
/// ```
/// use lockable::LockPool;
///
/// # (|| {
/// let pool = LockPool::new();
/// let guard1 = pool.blocking_lock(4);
/// let guard2 = pool.blocking_lock(5);
///
/// // This next line cannot acquire the lock because `4` is already locked on this thread
/// let guard3 = pool.try_lock(4);
/// assert!(guard3.is_none());
///
/// // After dropping the corresponding guard, we can lock it again
/// std::mem::drop(guard1);
/// let guard3 = pool.try_lock(4);
/// assert!(guard3.is_some());
/// # Ok::<(), lockable::Never>(())})().unwrap();
/// ```
#[inline]
pub fn try_lock(&self, key: K) -> Option<<Self as Lockable<K, ()>>::Guard<'_>> {
self.map
.try_lock(key, SyncLimit::no_limit())
.infallible_unwrap()
}
// TODO Add this
// /// Attempts to acquire the lock with the given key.
// ///
// /// This is identical to [LockPool::try_lock], please see documentation for that function for more information.
// /// But different to [LockPool::try_lock], [LockPool::try_lock_owned] works on an `Arc<LockPool>`
// /// instead of a [LockPool] and returns a [Lockable::OwnedGuard] that binds its lifetime to the [LockPool] in that [Arc].
// /// Such a [Lockable::OwnedGuard] can be more easily moved around or cloned than the [Lockable::Guard] returned by [LockPool::try_lock].
// ///
// /// Examples
// /// -----
// /// ```
// /// use lockable::LockPool;
// /// use std::sync::Arc;
// ///
// /// # (||{
// /// let pool = Arc::new(LockPool::new());
// /// let guard1 = pool.blocking_lock(4);
// /// let guard2 = pool.blocking_lock(5);
// ///
// /// // This next line cannot acquire the lock because `4` is already locked on this thread
// /// let guard3 = pool.try_lock_owned(4);
// /// assert!(guard3.is_none());
// ///
// /// // After dropping the corresponding guard, we can lock it again
// /// std::mem::drop(guard1);
// /// let guard3 = pool.try_lock_owned(4);
// /// assert!(guard3.is_some());
// /// # Ok::<(), lockable::Never>(())})().unwrap();
// /// ```
// #[inline]
// pub fn try_lock_owned(
// self: &Arc<Self>,
// key: K,
// ) -> Option<<Self as Lockable<K, ()>>::OwnedGuard> {
// self.map
// .try_lock_owned(key, SyncLimit::no_limit())
// .infallible_unwrap()
// }
/// Attempts to acquire the lock with the given key.
///
/// This is identical to [LockPool::try_lock], please see documentation for that function for more information.
/// But different to [LockPool::try_lock], [LockPool::try_lock_async] takes an [AsyncLimit] instead of a [SyncLimit]
/// and therefore allows an `async` callback to be specified for when the cache reaches its limit.
///
/// This function does not block and can be used in async contexts.
///
/// Examples
/// -----
/// ```
/// use lockable::LockPool;
/// use std::sync::Arc;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let pool = LockPool::new();
/// let guard1 = pool.async_lock(4).await;
/// let guard2 = pool.async_lock(5).await;
///
/// // This next line cannot acquire the lock because `4` is already locked on this thread
/// let guard3 = pool
/// .try_lock_async(4)
/// .await;
/// assert!(guard3.is_none());
///
/// // After dropping the corresponding guard, we can lock it again
/// std::mem::drop(guard1);
/// let guard3 = pool
/// .try_lock_async(4)
/// .await;
/// assert!(guard3.is_some());
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
#[inline]
pub async fn try_lock_async(&self, key: K) -> Option<<Self as Lockable<K, ()>>::Guard<'_>> {
self.map
.try_lock_async(key, AsyncLimit::no_limit())
.await
.infallible_unwrap()
}
// TODO Add this
// /// Attempts to acquire the lock with the given key.
// ///
// /// This is identical to [LockPool::try_lock_async], please see documentation for that function for more information.
// /// But different to [LockPool::try_lock_async], [LockPool::try_lock_owned_async] works on an `Arc<LockPool>`
// /// instead of a [LockPool] and returns a [Lockable::OwnedGuard] that binds its lifetime to the [LockPool] in that [Arc].
// /// Such a [Lockable::OwnedGuard] can be more easily moved around or cloned than the [Lockable::Guard] returned by [LockPool::try_lock_async].
// ///
// /// This is identical to [LockPool::try_lock_owned], please see documentation for that function for more information.
// /// But different to [LockPool::try_lock_owned], [LockPool::try_lock_owned_async] takes an [AsyncLimit] instead of a [SyncLimit]
// /// and therefore allows an `async` callback to be specified for when the cache reaches its limit.
// ///
// /// Examples
// /// -----
// /// ```
// /// use lockable::LockPool;
// /// use std::sync::Arc;
// ///
// /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
// /// let pool = Arc::new(LockPool::new());
// /// let guard1 = pool.async_lock(4, ).await;
// /// let guard2 = pool.async_lock(5, ).await;
// ///
// /// // This next line cannot acquire the lock because `4` is already locked on this thread
// /// let guard3 = pool
// /// .try_lock_owned_async(4, )
// /// .await;
// /// assert!(guard3.is_none());
// ///
// /// // After dropping the corresponding guard, we can lock it again
// /// std::mem::drop(guard1);
// /// let guard3 = pool
// /// .try_lock_owned_async(4, )
// /// .await;
// /// assert!(guard3.is_some());
// /// # Ok::<(), lockable::Never>(())}).unwrap();
// /// ```
// #[inline]
// pub async fn try_lock_owned_async(
// self: &Arc<Self>,
// key: K,
// ) -> Option<<Self as Lockable<K, ()>>::OwnedGuard> {
// self.map
// .try_lock_owned_async(key, AsyncLimit::no_limit())
// .await
// .infallible_unwrap()
// }
/// Lock a key and return a guard for it.
///
/// Locking a key prevents any other tasks from locking the same key.
///
/// If the lock with this key is currently locked by a different task, then the current tasks `await`s until it becomes available.
/// Upon returning, the task is the only task with the lock held. A RAII guard is returned to allow scoped unlock
/// of the lock. When the guard goes out of scope, the lock will be unlocked.
///
/// Examples
/// -----
/// ```
/// use lockable::LockPool;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let pool = LockPool::new();
/// let guard1 = pool.async_lock(4).await;
/// let guard2 = pool.async_lock(5).await;
///
/// // This next line would cause a deadlock or panic because `4` is already locked on this thread
/// // let guard3 = pool.async_lock(4).await;
///
/// // After dropping the corresponding guard, we can lock it again
/// std::mem::drop(guard1);
/// let guard3 = pool.async_lock(4).await;
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
#[inline]
pub async fn async_lock(&self, key: K) -> <Self as Lockable<K, ()>>::Guard<'_> {
self.map
.async_lock(key, AsyncLimit::no_limit())
.await
.infallible_unwrap()
}
// TODO Add this
// /// Lock a key and return a guard for it.
// ///
// /// This is identical to [LockPool::async_lock], please see documentation for that function for more information.
// /// But different to [LockPool::async_lock], [LockPool::async_lock_owned] works on an `Arc<LockPool>`
// /// instead of a [LockPool] and returns a [Lockable::OwnedGuard] that binds its lifetime to the [LockPool] in that [Arc].
// /// Such a [Lockable::OwnedGuard] can be more easily moved around or cloned than the [Lockable::Guard] returned by [LockPool::async_lock].
// ///
// /// Examples
// /// -----
// /// ```
// /// use lockable::LockPool;
// /// use std::sync::Arc;
// ///
// /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
// /// let pool = Arc::new(LockPool::new());
// /// let guard1 = pool
// /// .async_lock_owned(4)
// /// .await;
// /// let guard2 = pool
// /// .async_lock_owned(5)
// /// .await;
// ///
// /// // This next line would cause a deadlock or panic because `4` is already locked on this thread
// /// // let guard3 = pool.async_lock_owned(4).await;
// ///
// /// // After dropping the corresponding guard, we can lock it again
// /// std::mem::drop(guard1);
// /// let guard3 = pool
// /// .async_lock_owned(4)
// /// .await;
// /// # Ok::<(), lockable::Never>(())}).unwrap();
// /// ```
// #[inline]
// pub async fn async_lock_owned(
// self: &Arc<Self>,
// key: K,
// ) -> <Self as Lockable<K, ()>>::OwnedGuard {
// self.map
// .async_lock_owned(key, AsyncLimit::no_limit())
// .await
// .infallible_unwrap()
// }
/// Returns all of the keys that are currently locked.
///
/// This function has a high performance cost because it needs to lock the whole
/// map to get a consistent snapshot and clone all the keys.
///
/// Examples
/// -----
/// ```
/// use lockable::LockPool;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let pool = LockPool::new();
///
/// // Lock two keys
/// let guard1 = pool
/// .async_lock(4)
/// .await;
/// let guard2 = pool
/// .async_lock(5)
/// .await;
///
/// let keys: Vec<i64> = pool.locked_keys();
///
/// // `keys` now contains both keys
/// assert_eq!(2, keys.len());
/// assert!(keys.contains(&4));
/// assert!(keys.contains(&5));
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
#[inline]
pub fn locked_keys(&self) -> Vec<K> {
self.map.keys_with_entries_or_locked()
}
}
impl<K> Default for LockPool<K>
where
K: Eq + PartialEq + Hash + Clone,
{
fn default() -> Self {
Self::new()
}
}