Class: LoadTest::Future
- Inherits:
-
Object
- Object
- LoadTest::Future
- Defined in:
- lib/load_test/future.rb
Overview
Make parallelism by processes manageable.
Instance Attribute Summary collapse
-
#pid ⇒ Object
readonly
process id.
-
#reader ⇒ Object
readonly
reader of IO.pipe.
Class Method Summary collapse
-
.all(futures) ⇒ Object
Wait until all futures have completed.
-
.race(futures) ⇒ Object
Get the first completed future.
Instance Method Summary collapse
-
#abort ⇒ Object
Abort the future.
-
#initialize(&block) ⇒ Future
constructor
Execute the processing of the block asynchronously.
-
#take ⇒ Object
Wait until the process is completed and return the result.
-
#wait ⇒ Object
Wait for the process to complete.
Constructor Details
#initialize(&block) ⇒ Future
Execute the processing of the block asynchronously.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/load_test/future.rb', line 23 def initialize(&block) reader, writer = IO.pipe @pid = fork do reader.close begin result = block.call rescue => e result = e end Marshal.dump(result, writer) end writer.close @reader = reader @is_done = false end |
Instance Attribute Details
#pid ⇒ Object (readonly)
process id
4 5 6 |
# File 'lib/load_test/future.rb', line 4 def pid @pid end |
#reader ⇒ Object (readonly)
reader of IO.pipe
6 7 8 |
# File 'lib/load_test/future.rb', line 6 def reader @reader end |
Class Method Details
.all(futures) ⇒ Object
Wait until all futures have completed.
17 18 19 |
# File 'lib/load_test/future.rb', line 17 def all(futures) futures.each(&:wait) end |
.race(futures) ⇒ Object
Get the first completed future.
10 11 12 13 14 |
# File 'lib/load_test/future.rb', line 10 def race(futures) hash = futures.to_h { [_1.reader, _1] } readers, = IO.select(futures.map(&:reader)) hash[readers[0]] end |
Instance Method Details
#abort ⇒ Object
Abort the future.
59 60 61 62 63 |
# File 'lib/load_test/future.rb', line 59 def abort Process.kill(:INT, @pid) @reader.close @is_done = true end |
#take ⇒ Object
Wait until the process is completed and return the result.
50 51 52 53 54 55 56 |
# File 'lib/load_test/future.rb', line 50 def take wait result = Marshal.load(@reader) @reader.close raise result if result.is_a?(Exception) result end |
#wait ⇒ Object
Wait for the process to complete.
42 43 44 45 46 47 |
# File 'lib/load_test/future.rb', line 42 def wait return if @is_done Process.waitpid(@pid) @is_done = true self end |