|
|
@@ -0,0 +1,60 @@
|
|
|
+use std::sync::{Arc, Mutex};
|
|
|
+use tokio::time::{sleep, Duration};
|
|
|
+use std::collections::VecDeque;
|
|
|
+
|
|
|
+struct Bot {
|
|
|
+ shared_data: Arc<Mutex<VecDeque<u8>>>,
|
|
|
+}
|
|
|
+
|
|
|
+impl Bot {
|
|
|
+ pub fn new() -> Self {
|
|
|
+ Bot {
|
|
|
+ shared_data: Arc::new(Mutex::new(VecDeque::new())),
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn run1(&self) {
|
|
|
+ loop {
|
|
|
+ let data = {
|
|
|
+ let lock = self.shared_data.lock().unwrap();
|
|
|
+ lock.clone()
|
|
|
+ };
|
|
|
+
|
|
|
+ println!("Reading data: {:?}", data);
|
|
|
+
|
|
|
+ sleep(Duration::from_secs(1)).await;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn run2(&self) {
|
|
|
+ let mut counter: u8 = 0;
|
|
|
+
|
|
|
+ loop {
|
|
|
+ {
|
|
|
+ let mut lock = self.shared_data.lock().unwrap();
|
|
|
+ lock.push_back(counter);
|
|
|
+ }
|
|
|
+
|
|
|
+ println!("Writing data: {}", counter);
|
|
|
+
|
|
|
+ counter = counter.wrapping_add(1);
|
|
|
+
|
|
|
+ sleep(Duration::from_secs(1)).await;
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+#[tokio::test]
|
|
|
+async fn test_arc() {
|
|
|
+ let bot = Bot::new();
|
|
|
+
|
|
|
+ let bot = Arc::new(bot);
|
|
|
+
|
|
|
+ let bot1 = Arc::clone(&bot);
|
|
|
+ let bot2 = Arc::clone(&bot);
|
|
|
+
|
|
|
+ let run1_handle = tokio::spawn(async move { bot1.run1().await });
|
|
|
+ let run2_handle = tokio::spawn(async move { bot2.run2().await });
|
|
|
+
|
|
|
+ let _ = tokio::try_join!(run1_handle, run2_handle);
|
|
|
+}
|