File tree 1 file changed +67
-0
lines changed
1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env ruby
2
+
3
+ # asynchronous - using blocking Fiber primitive
4
+ def nap
5
+ # puts "you now have to wait, while I nap..."
6
+ sleep 3
7
+ # puts "...and now I'm awake, you can move along."
8
+ end
9
+
10
+ puts "blocking asynchronous execution, using the Fiber primitive"
11
+ fiber = Fiber . new do
12
+ nap
13
+ nap
14
+ end
15
+
16
+ fiber . resume
17
+ puts "blocking fibers are so boring."
18
+
19
+ # asynchronous - non-blocking fiber using Async gem
20
+ require 'async'
21
+
22
+ def nap_async
23
+ Async do |task |
24
+ # puts "you now have to wait, while I nap..."
25
+ sleep 3
26
+ # puts "...and now I'm awake, you can move along."
27
+ end
28
+ end
29
+
30
+ puts "non-blocking asynchronous execution, using the Async gem"
31
+
32
+ Async do
33
+ nap_async
34
+ nap_async
35
+ end
36
+
37
+ puts "non-blocking fibers are so much fun!"
38
+
39
+ # benchmark
40
+ require 'benchmark'
41
+
42
+ Benchmark . bm do |x |
43
+ # sequential version
44
+ x . report ( 'sequential' ) { 3 . times { nap } }
45
+
46
+ # blocking fiber version
47
+ x . report ( 'blocking fiber' ) {
48
+ 3 . times . map do
49
+ fiber = Fiber . new do
50
+ nap
51
+ end
52
+
53
+ fiber . resume
54
+ end
55
+ }
56
+
57
+ # non-blocking fiber version
58
+ x . report ( 'non-blocking fiber' ) {
59
+ Async do
60
+ 3 . times . map do
61
+ Async do
62
+ nap_async
63
+ end
64
+ end
65
+ end
66
+ }
67
+ end
You can’t perform that action at this time.
0 commit comments