Skip to content

Commit 2d6c5da

Browse files
committed
Add example showing greedy scheduling.
1 parent 92319f8 commit 2d6c5da

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

examples/count/fibers.rb

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#!/usr/bin/env ruby
2+
3+
require 'async'
4+
require 'benchmark'
5+
6+
transitions = []
7+
8+
puts "=========== FIBERS ==========="
9+
puts
10+
count = 0
11+
time = Benchmark.measure do
12+
Sync do
13+
5.times do
14+
[
15+
Async do ; transitions << "A1"
16+
puts "Task 1: count is #{count}" ; transitions << "A2"
17+
count += 1 ; transitions << "A3"
18+
sleep(0.1) ; transitions << "A4"
19+
end,
20+
Async do ; transitions << "B1"
21+
puts "Task 2: count is #{count}" ; transitions << "B2"
22+
count += 1 ; transitions << "B3"
23+
sleep(0.1) ; transitions << "B4"
24+
end
25+
].map(&:wait)
26+
end
27+
end
28+
end
29+
puts "#{time.real.round(2)} seconds to run. Final count is #{count}"
30+
puts transitions.join(" ")

examples/count/threads.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/usr/bin/env ruby
2+
3+
require 'benchmark'
4+
5+
transitions = []
6+
7+
puts "=========== THREADS ==========="
8+
puts
9+
count = 0
10+
time = Benchmark.measure do
11+
5.times do
12+
[
13+
Thread.new do ; transitions << "A1"
14+
puts "Task 1: count is #{count}" ; transitions << "A2"
15+
count += 1 ; transitions << "A3"
16+
sleep(0.1) ; transitions << "A4"
17+
end,
18+
Thread.new do ; transitions << "B1"
19+
puts "Task 2: count is #{count}" ; transitions << "B2"
20+
count += 1 ; transitions << "B3"
21+
sleep(0.1) ; transitions << "B4"
22+
end
23+
].map(&:join)
24+
end
25+
end
26+
puts "#{time.real.round(2)} seconds to run. Final count is #{count}"
27+
puts transitions.join(" ")

0 commit comments

Comments
 (0)