Skip to content

Commit

Permalink
change pattern for ::IO.pipe
Browse files Browse the repository at this point in the history
  • Loading branch information
ikatz-drizly committed Jun 29, 2021
1 parent 3ddccac commit 1be2c16
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions lib/piperator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,24 +60,23 @@ def self.wrap(value)
# @yieldparam io_r [IO] readable IO
def self.infinite_io(enumerator)
stop = false
io_r, io_w = ::IO.pipe # not the IO from this library
::IO.pipe do |io_r, io_w| # not the IO from this library

# a thread writes all the data to the pipe. the pipe automatically buffers everything for us
thr = Thread.new do
enumerator.each do |chunk|
break if stop
io_w.write(chunk)
# a thread writes all the data to the pipe. the pipe automatically buffers everything for us
thr = Thread.new do
enumerator.each do |chunk|
break if stop
io_w.write(chunk)
end
ensure
io_w.close # otherwise a read will hang
end

yield io_r
ensure
io_w.close
stop = true
thr.join
end

yield io_r
ensure
stop = true
io_r.read until io_r.eof? # must drain, or risk closing before writes finish -- broken pipe
io_r.close # must close ???
thr.join # must ensure that all data desired to be written is actually written
end

end

0 comments on commit 1be2c16

Please sign in to comment.