Skip to content

Commit

Permalink
Add example showing greedy scheduling.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Mar 1, 2024
1 parent 92319f8 commit 2d6c5da
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
30 changes: 30 additions & 0 deletions examples/count/fibers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env ruby

require 'async'
require 'benchmark'

transitions = []

puts "=========== FIBERS ==========="
puts
count = 0
time = Benchmark.measure do
Sync do
5.times do
[
Async do ; transitions << "A1"
puts "Task 1: count is #{count}" ; transitions << "A2"
count += 1 ; transitions << "A3"
sleep(0.1) ; transitions << "A4"
end,
Async do ; transitions << "B1"
puts "Task 2: count is #{count}" ; transitions << "B2"
count += 1 ; transitions << "B3"
sleep(0.1) ; transitions << "B4"
end
].map(&:wait)
end
end
end
puts "#{time.real.round(2)} seconds to run. Final count is #{count}"
puts transitions.join(" ")
27 changes: 27 additions & 0 deletions examples/count/threads.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/env ruby

require 'benchmark'

transitions = []

puts "=========== THREADS ==========="
puts
count = 0
time = Benchmark.measure do
5.times do
[
Thread.new do ; transitions << "A1"
puts "Task 1: count is #{count}" ; transitions << "A2"
count += 1 ; transitions << "A3"
sleep(0.1) ; transitions << "A4"
end,
Thread.new do ; transitions << "B1"
puts "Task 2: count is #{count}" ; transitions << "B2"
count += 1 ; transitions << "B3"
sleep(0.1) ; transitions << "B4"
end
].map(&:join)
end
end
puts "#{time.real.round(2)} seconds to run. Final count is #{count}"
puts transitions.join(" ")

0 comments on commit 2d6c5da

Please sign in to comment.