Class: RactorIO
- Inherits:
-
Object
- Object
- RactorIO
- Defined in:
- lib/ractor_io.rb
Overview
this class loads the contents of a file using a Ractor so that it’s running outside your main Ractor.
Usage:
rio = RactorIO.new.read('/tmp/a_large_file.txt') # read a file
... do other stuff ...
# optional loop until the file is read
loop do
break if rio.ready?
sleep 1
end
rio.string # contains the contents of the file as one large String
Instance Attribute Summary collapse
-
#string ⇒ Object
readonly
Returns the value of attribute string.
Instance Method Summary collapse
-
#initialize(move: false) ⇒ RactorIO
constructor
move: if true, the Ractor will yield the loaded file using the
moveoption of Ractor::yield. -
#read(path) ⇒ Object
this method returns immediately and loads the file in the background.
- #ready? ⇒ Boolean
Constructor Details
#initialize(move: false) ⇒ RactorIO
move: if true, the Ractor will yield the loaded file using the move option of Ractor::yield.
default: false
NOTE: as of this writing, and having tested this against Ruby 3.1.x and
3.2.x, setting the `move` option to `true' for large amounts of data
seems to cause a crash, at least on macOS. as a result this option is set
to `false` by default, which will result in a lot of memory copying, and
therefore increasing total memory consumption.
In the meantime, see also https://github.com/jefflunt/thread_io -
basically the same library as this, but using Threads only instead of
Ractors, which has the advantage of sharing memory, if that's important to
you. I haven't done extensive performance testing, so the perfornace
difference between ractor_io and thread_io might not be very large for
your particular use case.
33 34 35 36 37 |
# File 'lib/ractor_io.rb', line 33 def initialize(move: false) @move = move @ready = false @string = nil end |
Instance Attribute Details
#string ⇒ Object (readonly)
Returns the value of attribute string.
16 17 18 |
# File 'lib/ractor_io.rb', line 16 def string @string end |
Instance Method Details
#read(path) ⇒ Object
this method returns immediately and loads the file in the background
path: the path to the file you want to read.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/ractor_io.rb', line 42 def read(path) Thread.new do @ready = false @string = nil r = Ractor.new do Ractor.yield(IO.read(Ractor.receive), move: @move) end r.send(path) @string = r.take @ready = true nil end nil end |
#ready? ⇒ Boolean
59 60 61 |
# File 'lib/ractor_io.rb', line 59 def ready? @ready end |