shared.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. use std::sync::Arc;
  2. use tokio::sync::{Mutex, MutexGuard};
  3. use tokio::time::{timeout, Duration};
  4. // #[derive(Clone)] See issue #2
  5. pub struct Shared<T> {
  6. pub data: Arc<Mutex<T>>,
  7. /// Number of seconds to consider a dead lock
  8. pub lock_timeout: u64,
  9. }
  10. impl<T> Clone for Shared<T> {
  11. fn clone(&self) -> Self {
  12. Self {
  13. data: self.data.clone(),
  14. lock_timeout: self.lock_timeout,
  15. }
  16. }
  17. }
  18. impl<T> Shared<T> {
  19. /// Creates a new Shared of data T
  20. ///
  21. /// A lock timeout of 30 seconds is assigned by default (Use Shared::with_timeout to set the timeout yourself, or just edit the field as it is public)
  22. ///
  23. /// > Want to see a complete example, look at doc_example in the examples directory
  24. ///
  25. /// Example:
  26. /// ```
  27. /// use shared::Shared;
  28. ///
  29. /// // #[derive(Clone)]
  30. /// // Clone is no longer needed as of v0.2.0
  31. /// #[derive(Debug)]
  32. /// struct Person {
  33. /// pub name: String,
  34. /// pub age: u16
  35. /// }
  36. ///
  37. /// #[tokio::main]
  38. /// async fn main() {
  39. /// let shared_data = Shared::new(Person{
  40. /// name: "Test Dummy".to_string(),
  41. /// age: 30
  42. /// });
  43. /// }
  44. /// ```
  45. pub fn new(data: T) -> Self {
  46. Shared {
  47. data: Arc::new(Mutex::new(data)),
  48. lock_timeout: 30_u64,
  49. }
  50. }
  51. /// Creates a new Shared of data T with a given timeout in seconds
  52. pub fn with_timeout(data: T, timeout: u64) -> Self {
  53. Shared { data: Arc::new(Mutex::new(data)), lock_timeout: timeout }
  54. }
  55. /// Acquire lock
  56. ///
  57. /// Will wait so many seconds as defined by lock_timeout (This will panic once the timeout is reached)
  58. ///
  59. /// > Want to see a complete example, look at doc_example in the examples directory
  60. ///
  61. /// Using:
  62. /// ```
  63. /// // See Shared::new for creating a Shared<Person>
  64. ///
  65. /// { // Direct access
  66. /// let person = shared_data.lock().await;
  67. /// println!("{:?}", person);
  68. /// }
  69. ///
  70. /// // Using it as a parameter
  71. /// async fn get_older(shared: Shared<Person>) {
  72. /// let mut person = shared.lock().await;
  73. /// person.age += 1;
  74. /// }
  75. ///
  76. /// // Calling
  77. /// get_older(shared_data.clone()).await;
  78. /// ```
  79. pub async fn lock(&self) -> MutexGuard<'_, T> {
  80. let result = timeout(Duration::from_secs(self.lock_timeout), self.data.lock()).await;
  81. if let Ok(guard) = result {
  82. return guard;
  83. }
  84. panic!(
  85. "Failed to acquire lock in {} seconds. Deadlock?",
  86. self.lock_timeout
  87. );
  88. // self.data.lock().await
  89. }
  90. }