Skip to content

Commit e04bec5

Browse files
committed
perf: Reduce channel lock contention for drop-threads
1 parent 7406f46 commit e04bec5

2 files changed

Lines changed: 28 additions & 2 deletions

File tree

crates/span/src/map.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,22 @@ impl Drop for SpanMap {
163163
let (sender, receiver) = std::sync::mpsc::channel::<(SendPtr, fn(SendPtr))>();
164164
std::thread::Builder::new()
165165
.name("SpanMapDropper".to_owned())
166-
.spawn(move || receiver.iter().for_each(|(b, drop)| drop(b)))
166+
.spawn(move || {
167+
loop {
168+
// block on a receive
169+
if let Ok((b, drop)) = receiver.recv() {
170+
drop(b);
171+
}
172+
// then drain the entire channel
173+
while let Ok((b, drop)) = receiver.try_recv() {
174+
drop(b);
175+
}
176+
// and sleep for a bit
177+
std::thread::sleep(std::time::Duration::from_millis(100));
178+
}
179+
// why do this over just a `receiver.iter().for_each(drop)`? To reduce contention on the channel lock.
180+
// otherwise this thread will constantly wake up and sleep again.
181+
})
167182
.unwrap();
168183
sender
169184
})

crates/syntax/src/lib.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,18 @@ impl<T> Drop for Parse<T> {
218218
let (sender, receiver) = std::sync::mpsc::channel::<GreenNode>();
219219
std::thread::Builder::new()
220220
.name("ParseNodeDropper".to_owned())
221-
.spawn(move || receiver.iter().for_each(drop))
221+
.spawn(move || {
222+
loop {
223+
// block on a receive
224+
_ = receiver.recv();
225+
// then drain the entire channel
226+
while let Ok(_) = receiver.try_recv() {}
227+
// and sleep for a bit
228+
std::thread::sleep(std::time::Duration::from_millis(100));
229+
}
230+
// why do this over just a `receiver.iter().for_each(drop)`? To reduce contention on the channel lock.
231+
// otherwise this thread will constantly wake up and sleep again.
232+
})
222233
.unwrap();
223234
sender
224235
})

0 commit comments

Comments
 (0)