Exercise 07-12
authorGreg Burri <greg.burri@gmail.com>
Sat, 26 Oct 2024 10:46:11 +0000 (12:46 +0200)
committerGreg Burri <greg.burri@gmail.com>
Sat, 26 Oct 2024 10:46:11 +0000 (12:46 +0200)
exercises/07_threads/12_rw_lock/src/lib.rs
exercises/07_threads/12_rw_lock/src/store.rs

index 0c33f53..9282a36 100644 (file)
@@ -1,7 +1,7 @@
 // TODO: Replace `Mutex` with `RwLock` in the `TicketStore` struct and
 //  all other relevant places to allow multiple readers to access the ticket store concurrently.
 use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError};
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, RwLock};
 
 use crate::data::{Ticket, TicketDraft};
 use crate::store::{TicketId, TicketStore};
@@ -26,7 +26,7 @@ impl TicketStoreClient {
         Ok(response_receiver.recv().unwrap())
     }
 
-    pub fn get(&self, id: TicketId) -> Result<Option<Arc<Mutex<Ticket>>>, OverloadedError> {
+    pub fn get(&self, id: TicketId) -> Result<Option<Arc<RwLock<Ticket>>>, OverloadedError> {
         let (response_sender, response_receiver) = sync_channel(1);
         self.sender
             .try_send(Command::Get {
@@ -55,11 +55,11 @@ enum Command {
     },
     Get {
         id: TicketId,
-        response_channel: SyncSender<Option<Arc<Mutex<Ticket>>>>,
+        response_channel: SyncSender<Option<Arc<RwLock<Ticket>>>>,
     },
 }
 
-pub fn server(receiver: Receiver<Command>) {
+fn server(receiver: Receiver<Command>) {
     let mut store = TicketStore::new();
     loop {
         match receiver.recv() {
index 7387efd..c70867c 100644 (file)
@@ -1,13 +1,13 @@
 use crate::data::{Status, Ticket, TicketDraft};
 use std::collections::BTreeMap;
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, RwLock};
 
 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 pub struct TicketId(u64);
 
 #[derive(Clone)]
 pub struct TicketStore {
-    tickets: BTreeMap<TicketId, Arc<Mutex<Ticket>>>,
+    tickets: BTreeMap<TicketId, Arc<RwLock<Ticket>>>,
     counter: u64,
 }
 
@@ -28,14 +28,14 @@ impl TicketStore {
             description: ticket.description,
             status: Status::ToDo,
         };
-        let ticket = Arc::new(Mutex::new(ticket));
+        let ticket = Arc::new(RwLock::new(ticket));
         self.tickets.insert(id, ticket);
         id
     }
 
     // The `get` method should return a handle to the ticket
     // which allows the caller to either read or modify the ticket.
-    pub fn get(&self, id: TicketId) -> Option<Arc<Mutex<Ticket>>> {
+    pub fn get(&self, id: TicketId) -> Option<Arc<RwLock<Ticket>>> {
         self.tickets.get(&id).cloned()
     }
 }