sync: make TokenBucket::close into a destructor in example (#6032)

This commit is contained in:
Alice Ryhl 2023-09-24 14:16:14 +02:00 committed by GitHub
parent 707fb4d0df
commit 02aacf5110
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -147,7 +147,7 @@ use std::sync::Arc;
/// [token bucket]: https://en.wikipedia.org/wiki/Token_bucket /// [token bucket]: https://en.wikipedia.org/wiki/Token_bucket
/// ``` /// ```
/// use std::sync::Arc; /// use std::sync::Arc;
/// use tokio::sync::{AcquireError, Semaphore}; /// use tokio::sync::Semaphore;
/// use tokio::time::{interval, Duration}; /// use tokio::time::{interval, Duration};
/// ///
/// struct TokenBucket { /// struct TokenBucket {
@ -179,30 +179,34 @@ use std::sync::Arc;
/// Self { jh, sem } /// Self { jh, sem }
/// } /// }
/// ///
/// async fn acquire(&self) -> Result<(), AcquireError> { /// async fn acquire(&self) {
/// self.sem.acquire().await.map(|p| p.forget()) /// // This can return an error if the semaphore is closed, but we
/// // never close it, so just ignore errors.
/// let _ = self.sem.acquire().await;
/// } /// }
/// }
/// ///
/// async fn close(self) { /// impl Drop for TokenBucket {
/// self.sem.close(); /// fn drop(&mut self) {
/// // Kill the background task so it stops taking up resources when we
/// // don't need it anymore.
/// self.jh.abort(); /// self.jh.abort();
/// let _ = self.jh.await;
/// } /// }
/// } /// }
/// ///
/// #[tokio::main] /// #[tokio::main]
/// # async fn _hidden() {}
/// # #[tokio::main(flavor = "current_thread", start_paused = true)]
/// async fn main() { /// async fn main() {
/// let capacity = 5; // operation per second /// let capacity = 5;
/// let update_interval = Duration::from_secs_f32(1.0 / capacity as f32); /// let update_interval = Duration::from_secs_f32(1.0 / capacity as f32);
/// let bucket = TokenBucket::new(update_interval, capacity); /// let bucket = TokenBucket::new(update_interval, capacity);
/// ///
/// for _ in 0..5 { /// for _ in 0..5 {
/// bucket.acquire().await.unwrap(); /// bucket.acquire().await;
/// ///
/// // do the operation /// // do the operation
/// } /// }
///
/// bucket.close().await;
/// } /// }
/// ``` /// ```
/// ///