Skip to content

Commit

Permalink
Reduce CPU load
Browse files Browse the repository at this point in the history
`Fiber.yield` sleeps for 0 seconds. When used in a loop, this,
effectively, maxes out CPU if there are no other resumable fibers.
  • Loading branch information
akadusei committed Feb 14, 2024
1 parent 917b433 commit f1135cf
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased] -

### Fixed
- Replace `Fiber.yield` with `sleep 1.microsecond` in loops to reduce CPU load

## [0.18.0] - 2023-12-07

### Changed
Expand Down
4 changes: 2 additions & 2 deletions spec/mel_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ describe Mel do

100_000.times do
break if Mel.state.stopped?
Fiber.yield
sleep 1.microsecond
end

Mel.state.stopped?.should be_true
Expand All @@ -39,7 +39,7 @@ describe Mel do

100_000.times do
break if Mel.state.stopped?
Fiber.yield
sleep 1.microsecond
end

Mel.state.stopped?.should be_true
Expand Down
4 changes: 2 additions & 2 deletions src/worker.cr
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ module Mel
spawn { start }

until state.started?
Fiber.yield
sleep 1.microsecond
end
end

Expand All @@ -55,7 +55,7 @@ module Mel
lock { @@state = State::Stopping } unless state.stopped?

until state.stopped?
Fiber.yield
sleep 1.microsecond
end
end

Expand Down

0 comments on commit f1135cf

Please sign in to comment.