bus icon indicating copy to clipboard operation
bus copied to clipboard

recv() cpu abuse

Open h04x opened this issue 4 years ago • 3 comments

Hello. I'm new with Rust. 20 recv() uses 40% cpu on my linux box. Is this a known issue?

extern crate bus;
use bus::Bus;
use std::sync::{Arc, Mutex};
use std::thread;
use std::io;


fn main() {
    let bus: std::sync::Arc<std::sync::Mutex<bus::Bus<usize>>>
        = Arc::new(Mutex::new(Bus::new(10)));

    for _ in 0..20 {
        let mut rxb = bus.clone().lock().unwrap().add_rx();
        thread::spawn(move || loop {
            let msg = rxb.recv().unwrap();
        });
    }

    io::stdin().read_line(&mut String::new()).unwrap();
}

total

11909 root      20   0 1029148   1980   1700 S  39.2   0.1   1:01.07 bus_possible_bu

per thread

11926 root      20   0 1029148   1980   1700 R   2.7   0.1   0:00.19 bus_possible_bu
11927 root      20   0 1029148   1980   1700 R   2.7   0.1   0:00.19 bus_possible_bu
11931 root      20   0 1029148   1980   1700 R   2.7   0.1   0:00.19 bus_possible_bu

cpu

model name      : Intel(R) Core(TM) i3 CPU         540  @ 3.07GHz

h04x avatar Oct 22 '19 01:10 h04x

Ah, yes, those idle cycles stem from https://github.com/jonhoo/bus/blob/ec317a217d7745895cd7b9f95be7f62e20f1ff51/src/lib.rs#L405. There is at least one case where the readers race with the writer and may not successfully wake it up, so the writer has to park with a timeout. I would love to get rid of this, but haven't had a chance to dig into it, and no longer use this library actively myself. If you want to take a look, I'd be happy to help out!

jonhoo avatar Oct 22 '19 11:10 jonhoo

@jonhoo Would be great to note this problem in the README. With this problem the crate isn't exactly "Efficient". Perhaps suggest an alternative if this crate is no longer maintained.

I like its API, so thanks for putting it up!

xixixao avatar Dec 12 '20 05:12 xixixao

@xixixao Would you be up for writing up a quick PR that adds this note to the README? Seems completely reasonable to me :+1:

jonhoo avatar Dec 15 '20 02:12 jonhoo