From 20a7fbefb6691144c8d97d0ef14fef2671af84b6 Mon Sep 17 00:00:00 2001 From: Francesco Virga <127943050+CiccioVirga@users.noreply.github.com> Date: Tue, 25 Jun 2024 13:46:26 +0200 Subject: [PATCH] Update 2023-07-07.md aggiunta la soluzione alla domanda 4 --- .../Esami Rust/2023-07-07.md | 74 ++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/II - MAGISTRALE/II - [02GRSOV] Programmazione di Sistema/Esami Rust/2023-07-07.md b/II - MAGISTRALE/II - [02GRSOV] Programmazione di Sistema/Esami Rust/2023-07-07.md index 4e1c6e5..ca30746 100644 --- a/II - MAGISTRALE/II - [02GRSOV] Programmazione di Sistema/Esami Rust/2023-07-07.md +++ b/II - MAGISTRALE/II - [02GRSOV] Programmazione di Sistema/Esami Rust/2023-07-07.md @@ -84,7 +84,79 @@ Si implementi tale struttura dati nel linguaggio Rust, avendo cura di renderne i
Soluzione -> risposta non verificata +```rust +struct Item { + i: Instant, + t: T +} + +// ### Non credo che l'implementazione di questi trait possa essere richiesta ad un esame +// perché non sono correlati all'esercizio in sé ma al fatto che li richiede il BinaryHeap che è una coda con priorità +impl PartialEq for Item { + fn eq(&self, other: &Self) -> bool { + other.i.eq(&self.i) + } +} + +impl Eq for Item {} + +impl PartialOrd for Item { + fn partial_cmp(&self, other: &Self) -> Option { + other.i.partial_cmp(&self.i) + } +} + +impl Ord for Item { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + other.i.cmp(&self.i) + } +} +//#### + +pub struct DelayedQueue { + + data: Mutex>>, + cv: Condvar +} + +impl DelayedQueue { + + pub fn new() -> Self { + Self { + data: Mutex::new(BinaryHeap::new()), // + cv: Condvar::new() + } + } + + + pub fn offer(&self, t: T, i: Instant) { + let item = Item { i,t }; + + let mut data = self.data.lock().unwrap(); + data.push(item); + self.cv.notify_all(); + } + + pub fn Take(&self) -> Option { + let mut data = self.data.lock().unwrap(); + let i = data.peek().unwrap().i; + + while (!data.is_empty()) { + let now = Instant::now(); + + if i < now { + return Some(data.pop().unwrap().t) + } + + // l'attesa deve essere giusto il tempo necessario + + let duration = i.duration_since(now); + data = self.cv.wait_timeout(data, duration).unwrap().0 + } + None + } +} +```