Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,79 @@ Si implementi tale struttura dati nel linguaggio Rust, avendo cura di renderne i
<details>
<summary>Soluzione</summary>

> risposta non verificata
```rust
struct Item<T:Send> {
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<T: Send> PartialEq for Item<T> {
fn eq(&self, other: &Self) -> bool {
other.i.eq(&self.i)
}
}

impl <T: Send> Eq for Item<T> {}

impl<T: Send> PartialOrd for Item<T> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
other.i.partial_cmp(&self.i)
}
}

impl<T: Send> Ord for Item<T> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.i.cmp(&self.i)
}
}
//####

pub struct DelayedQueue<T: Send> {

data: Mutex<BinaryHeap<Item<T>>>,
cv: Condvar
}

impl <T: Send> DelayedQueue<T> {

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<T> {
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
}
}
```

</details>