karyon_core/async_runtime/
lock.rs1use 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#[cfg(feature = "smol")]
18pub type SemaphoreGuard = SemaphoreGuardArc;
19#[cfg(feature = "tokio")]
21pub type SemaphoreGuard = OwnedSemaphorePermit;
22
23pub struct Semaphore(Arc<RtSemaphore>);
40
41impl Semaphore {
42 pub fn new(permits: usize) -> Self {
44 Self(Arc::new(RtSemaphore::new(permits)))
45 }
46
47 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 drop(guard);
81 let _ = task.await;
82
83 let _guard = sem.acquire().await.unwrap();
85 });
86 }
87}