1234567891011121314151617181920212223242526272829303132333435363738394041 |
- use std::sync::Arc;
- use tokio::sync::{Mutex, MutexGuard};
- use tokio::time::{timeout, Duration};
- /// Provides a 30 second timeout for lock attempts
- const LOCK_TIMEOUT: u64 = 30;
- #[derive(Clone)]
- pub struct Shard<T> {
- pub data: Arc<Mutex<T>>,
- }
- impl<T> Shard<T> {
- pub fn new(data: T) -> Self {
- Shard {
- data: Arc::new(Mutex::new(data)),
- }
- }
- /// Acquire lock
- ///
- /// Using:
- /// ```
- /// {
- /// let data = shared.lock().await;
- /// // make changes to T
- /// }
- /// ```
- pub async fn lock(&self) -> MutexGuard<'_, T> {
- let result = timeout(Duration::from_secs(LOCK_TIMEOUT), self.data.lock()).await;
- if let Ok(guard) = result {
- return guard;
- }
- panic!(
- "Failed to acquire lock in {} seconds. Deadlock?",
- LOCK_TIMEOUT
- );
- // self.data.lock().await
- }
- }
|