Skip to main content

karyon_core/async_runtime/
lock.rs

1use std::sync::Arc;
2
3#[cfg(feature = "smol")]
4pub use smol::lock::{Mutex, MutexGuard, OnceCell, RwLock};
5
6#[cfg(feature = "tokio")]
7pub use tokio::sync::{Mutex, MutexGuard, OnceCell, RwLock};
8
9#[cfg(feature = "smol")]
10use smol::lock::{Semaphore as RtSemaphore, SemaphoreGuardArc};
11#[cfg(feature = "tokio")]
12use tokio::sync::{OwnedSemaphorePermit, Semaphore as RtSemaphore};
13
14use crate::Result;
15
16/// A permit from [`Semaphore`]. The permit is released on drop.
17#[cfg(feature = "smol")]
18pub type SemaphoreGuard = SemaphoreGuardArc;
19/// A permit from [`Semaphore`]. The permit is released on drop.
20#[cfg(feature = "tokio")]
21pub type SemaphoreGuard = OwnedSemaphorePermit;
22
23/// An async counting semaphore that works on both smol and tokio.
24///
25/// # Example
26///
27///```
28/// use karyon_core::async_runtime::lock::Semaphore;
29///
30///  async {
31///     let sem = Semaphore::new(2);
32///     let guard = sem.acquire().await.unwrap();
33///     // ...
34///     drop(guard);
35///  };
36///
37/// ```
38///
39pub struct Semaphore(Arc<RtSemaphore>);
40
41impl Semaphore {
42    /// Creates a new Semaphore with `permits` permits.
43    pub fn new(permits: usize) -> Self {
44        Self(Arc::new(RtSemaphore::new(permits)))
45    }
46
47    /// Waits for a permit. The returned guard can be moved into other tasks.
48    pub async fn acquire(&self) -> Result<SemaphoreGuard> {
49        #[cfg(feature = "smol")]
50        let guard = self.0.acquire_arc().await;
51        #[cfg(feature = "tokio")]
52        let guard = self.0.clone().acquire_owned().await?;
53
54        Ok(guard)
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use std::sync::Arc;
61
62    use crate::async_runtime::{block_on, spawn};
63
64    use super::*;
65
66    #[test]
67    fn test_semaphore() {
68        block_on(async {
69            let sem = Arc::new(Semaphore::new(1));
70            let guard = sem.acquire().await.unwrap();
71
72            let task = spawn({
73                let sem = sem.clone();
74                async move {
75                    let _guard = sem.acquire().await.unwrap();
76                }
77            });
78
79            // Release the permit so the task can take it.
80            drop(guard);
81            let _ = task.await;
82
83            // The task dropped its guard, so the permit is free again.
84            let _guard = sem.acquire().await.unwrap();
85        });
86    }
87}