0

I have a worker thread implemented something like this:

impl WorkerThread {
    fn new() -> Self {
        let (main_sender, thread_receiver) = crossbeam_channel::unbounded();
        let (thread_sender, main_receiver) = crossbeam_channel::unbounded();

        let _ = thread::spawn(move || loop {
            if let Ok(s) = thread_receiver.recv() {
                let result = do_work();

                thread_sender.send(result).unwrap();
            }
        });

        Self {
            main_sender,
            main_receiver,
        }
    }
}

Is this infinite loop considered a Busy Waiting? The documentation for the crossbeam_channel::Receiver::recv says:

Blocks the current thread until a message is received or the channel is empty and disconnected.

But what does this Blocks the current thread mean?

On my Ubuntu, I looked with htop on the CPU load and with this blocking call, I saw that only one core (the main thread) was busy. But if I replace recv() with non-blocking try_recv() the htop shows that my second core load increases up to 100%.

Can I assume the identical behavior on every platform (Linux, Mac, Windows, etc)? Or is it how my particular systems scheduler works?

nikitablack
  • 4,359
  • 2
  • 35
  • 68
  • 1
    'Blocking' means that it isn't busy-waiting. As it's documented that way, it should be the same on all platforms. – user207421 Jun 15 '22 at 12:54
  • @Caesar How's your answer relates to my question? I didn't ask about naming a thread. – nikitablack Jun 15 '22 at 13:13
  • 3
    @nikitablack Make sure you handle the error of `recv`, though, like this: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=5e8d3c0108ecaf1731d98da12437ab0a. If the channel gets closed, `recv` will return an error, and you should `break` out of the loop in that case. Otherwise you will be stuck at 100% CPU power receiving the same error over and over again. – Finomnis Jun 15 '22 at 13:21
  • See: [What does the term "blocking" mean in programming?](https://stackoverflow.com/questions/2407589/what-does-the-term-blocking-mean-in-programming) – John Kugelman Jun 22 '22 at 12:27

0 Answers0