complete chapter 7
Some checks failed
CI / gravity (push) Has been skipped
CI / build (push) Failing after 14s
CI / is_fresh (push) Successful in 49s
CI / formatter (push) Failing after 17s

This commit is contained in:
2025-05-02 14:11:16 +05:30
parent 4fbee2d894
commit b044878fe8
11 changed files with 90 additions and 31 deletions

View 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, Mutex, 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,7 +55,7 @@ enum Command {
},
Get {
id: TicketId,
response_channel: SyncSender<Option<Arc<Mutex<Ticket>>>>,
response_channel: SyncSender<Option<Arc<RwLock<Ticket>>>>,
},
}

View File

@@ -1,13 +1,13 @@
use crate::data::{Status, Ticket, TicketDraft};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, 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()
}
}