lib.rs 917 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. use std::sync::Arc;
  2. use tokio::sync::{Mutex, MutexGuard};
  3. use tokio::time::{timeout, Duration};
  4. /// Provides a 30 second timeout for lock attempts
  5. const LOCK_TIMEOUT: u64 = 30;
  6. #[derive(Clone)]
  7. pub struct Shard<T> {
  8. pub data: Arc<Mutex<T>>,
  9. }
  10. impl<T> Shard<T> {
  11. pub fn new(data: T) -> Self {
  12. Shard {
  13. data: Arc::new(Mutex::new(data)),
  14. }
  15. }
  16. /// Acquire lock
  17. ///
  18. /// Using:
  19. /// ```
  20. /// {
  21. /// let data = shared.lock().await;
  22. /// // make changes to T
  23. /// }
  24. /// ```
  25. pub async fn lock(&self) -> MutexGuard<'_, T> {
  26. let result = timeout(Duration::from_secs(LOCK_TIMEOUT), self.data.lock()).await;
  27. if let Ok(guard) = result {
  28. return guard;
  29. }
  30. panic!(
  31. "Failed to acquire lock in {} seconds. Deadlock?",
  32. LOCK_TIMEOUT
  33. );
  34. // self.data.lock().await
  35. }
  36. }