Skip to content

New lint: loop with atomics without other side effects #7809

@Kixunil

Description

@Kixunil

What it does

The lint would check that a loop has no side effects other than atomic access and warn to park the thread or call std::hint::spin_loop().

Categories (optional)

  • Kind: perf

What is the advantage of the recommended code over the original code

If the thread is parked it will stop consuming resources and avoid priority inversion.
If spin_loop() hint is used the code will consume less power on some architectures or perform better.
Presence of spin_loop() could also better communicate to reviewer that author did not forget to park the thread.

Drawbacks

None that I know of but I'm not very knowledgeable about the topic.
In some cases it may be better to use futex instead of thread::park().

Example

while some_atomic.load(atomic::Ordering::Acquire) == NOT_READY {}

Could be written as:

while some_atomic.load(atomic::Ordering::Acquire) == NOT_READY {
    std::hint::spin_loop();
}

or

while some_atomic.load(atomic::Ordering::Acquire) == NOT_READY {
    thread::park();
}

with thread::unpark() at the place where a value is stored into atomic

Additional context

Loosely related: rust-lang/miri#1388 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions