Avoid nested loops

This commit is contained in:
Ruihan Li
2024-09-01 18:54:17 +08:00
committed by Tate, Hongliang Tian
parent 25daab7e78
commit d70ae181b5

View File

@ -212,28 +212,20 @@ impl EpollFile {
}
fn pop_ready(&self, max_events: usize, ep_events: &mut Vec<EpollEvent>) -> usize {
let mut count_events = 0;
let mut ready = self.ready.lock();
let mut pop_quota = ready.len();
loop {
// Pop some ready entries per round.
//
// Since the popped ready entries may contain "false positive" and
// we want to return as many results as possible, this has to
// be done in a loop.
let pop_count = (max_events - count_events).min(pop_quota);
if pop_count == 0 {
let mut count_events = 0;
for _ in 0..ready.len() {
if count_events >= max_events {
break;
}
let ready_entries: Vec<Arc<EpollEntry>> = ready
.drain(..pop_count)
.filter_map(|entry| Weak::upgrade(&entry))
.collect();
pop_quota -= pop_count;
// Examine these ready entries, which are candidates for the results
// to be returned.
for entry in ready_entries {
let weak_entry = ready.pop_front().unwrap();
let Some(entry) = Weak::upgrade(&weak_entry) else {
// The entry has been deleted.
continue;
};
let (ep_event, ep_flags) = entry.event_and_flags();
// If this entry's file is ready, save it in the output array.
// EPOLLHUP and EPOLLERR should always be reported.
@ -250,7 +242,7 @@ impl EpollFile {
if !ready_events.is_empty()
&& !ep_flags.intersects(EpollFlags::ONE_SHOT | EpollFlags::EDGE_TRIGGER)
{
ready.push_back(Arc::downgrade(&entry));
ready.push_back(weak_entry);
}
// Otherwise, the entry is indeed removed the ready list and we should reset
// its ready flag.
@ -263,12 +255,12 @@ impl EpollFile {
}
}
}
}
// Clear the epoll file's events if no ready entries
if ready.len() == 0 {
self.pollee.del_events(IoEvents::IN);
}
count_events
}