Skip to content

loop { thread::yield_now(); } causes 100% CPU usage #46774

Closed
@pzmarzly

Description

@pzmarzly

I may be wrong, but I thought thread::yield_now() should work like thread::sleep_ms(1) (yes, I known there's preferred Duration struct). This may be caused by Linux kernel and not Rust's fault, but it leads to 100% CPU usage and PC heating up.

I tried this code:

use std::thread;
fn main() {
    for _ in 1..4 {
        thread::spawn(||  loop { thread::yield_now(); });
    }
    loop { thread::yield_now(); }
}

And ended up with 100% usage on 4-core CPU.

Meanwhile replacing thread::yield_now with thread::sleep_ms(1) drops usage to 0%. Also, following code using sync::mpsc (that according to documentation of yield_now() uses yield_now()) also (thankfully) uses 0% of CPU time:

use std::thread;
use std::sync::mpsc::channel;
fn main() {
    for _ in 1..4 {
        thread::spawn(|| {
            let (tx, rx) = channel();
            tx.send(1).unwrap();
            loop { rx.recv().unwrap(); }
        });
    }
    let (tx, rx) = channel();
    tx.send(1).unwrap();
    loop { rx.recv().unwrap(); }
}

rustc --version --verbose:

rustc 1.24.0-nightly (f8af59d95 2017-12-13)
binary: rustc
commit-hash: f8af59d95225d122e38bb5dceb1027844d4ce170
commit-date: 2017-12-13
host: x86_64-unknown-linux-gnu
release: 1.24.0-nightly
LLVM version: 4.0

uname -a: Linux pawel-pc 4.12.14-1-MANJARO #1 SMP PREEMPT Wed Sep 20 10:51:00 UTC 2017 x86_64 GNU/Linux

sudo cpupower frequency-info:

analyzing CPU 0:
  driver: intel_pstate
  CPUs which run at the same hardware frequency: 0
  CPUs which need to have their frequency coordinated by software: 0
  maximum transition latency:  Cannot determine or is not supported.
  hardware limits: 800 MHz - 3.20 GHz
  available cpufreq governors: performance powersave
  current policy: frequency should be within 800 MHz and 3.20 GHz.
                  The governor "powersave" may decide which speed to use
                  within this range.
  current CPU frequency: 1.40 GHz (asserted by call to hardware)
  boost state support:
    Supported: yes
    Active: yes

I tried both sudo cpupower frequency-set -g powersave and sudo cpupower frequency-set -g performance. I was running all te code with cargo run --release.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-mediumCall for participation: Medium difficulty. Experience needed to fix: Intermediate.P-mediumMedium priorityT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions