arc_test.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use std::sync::{Arc, Mutex};
  2. use tokio::time::{sleep, Duration};
  3. use std::collections::VecDeque;
  4. struct Bot {
  5. shared_data: Arc<Mutex<VecDeque<u8>>>,
  6. }
  7. impl Bot {
  8. pub fn new() -> Self {
  9. Bot {
  10. shared_data: Arc::new(Mutex::new(VecDeque::new())),
  11. }
  12. }
  13. pub async fn run1(&self) {
  14. loop {
  15. let data = {
  16. let lock = self.shared_data.lock().unwrap();
  17. lock.clone()
  18. };
  19. println!("Reading data: {:?}", data);
  20. sleep(Duration::from_secs(1)).await;
  21. }
  22. }
  23. pub async fn run2(&self) {
  24. let mut counter: u8 = 0;
  25. loop {
  26. {
  27. let mut lock = self.shared_data.lock().unwrap();
  28. lock.push_back(counter);
  29. }
  30. println!("Writing data: {}", counter);
  31. counter = counter.wrapping_add(1);
  32. sleep(Duration::from_secs(1)).await;
  33. }
  34. }
  35. }
  36. #[tokio::test]
  37. async fn test_arc() {
  38. let bot = Bot::new();
  39. let bot = Arc::new(bot);
  40. let bot1 = Arc::clone(&bot);
  41. let bot2 = Arc::clone(&bot);
  42. let run1_handle = tokio::spawn(async move { bot1.run1().await });
  43. let run2_handle = tokio::spawn(async move { bot2.run2().await });
  44. let _ = tokio::try_join!(run1_handle, run2_handle);
  45. }