Method: IO#await_writable

Defined in:
lib/all/io.rb

#await_writable(opts = {}) ⇒ true

Suspends the current evaluation until IO is writable.

While waiting, the code jumps to the event loop and executes other evaluations that are ready to run in the meantime.

Examples:

Waiting inside a evaluation

# Control flow is indicated by (N)

r,w = IO.pipe

# jam the pipe with x's, assuming the pipe's max capacity is 2^16 bytes
w.write 'x'*65536

# (1)
writer = concurrently do
  # (4)
  w.await_writable
  # (6)
  w.write 'I can write again!'
  :written
end

# (2)
concurrently do
  # (5)
  r.read 65536 # clear the pipe
end

# (3)
writer.await_result # => :written
# (7)

r.close; w.close

Waiting outside a evaluation

# Control flow is indicated by (N)

r,w = IO.pipe

# jam the pipe with x's, assuming the pipe's max capacity is 2^16 bytes
w.write 'x'*65536

# (1)
concurrently do
  # (3)
  puts "I'm running while the outside is waiting!"
  r.read 65536 # clear the pipe
end

# (2)
w.await_writable
# (4)

r.close; w.close

Waiting with a timeout

r,w = IO.pipe
# jam the pipe with x's, assuming the pipe's max capacity is 2^16 bytes
w.write 'x'*65536

w.await_writable(within: 1)
# => raises a TimeoutError after 1 second

Waiting with a timeout and a timeout result

r,w = IO.pipe
# jam the pipe with x's, assuming the pipe's max capacity is 2^16 bytes
w.write 'x'*65536

w.await_writable(within: 0.1, timeout_result: false)
# => returns false after 0.1 seconds

Options Hash (opts):

  • :within (Numeric)

    maximum time to wait (defaults to: Float::INFINITY)

  • :timeout_result (Object)

    result to return in case of an exceeded waiting time (defaults to raising Concurrently::Evaluation::TimeoutError)

Raises:

Since:

  • 1.0.0



252
253
254
255
256
257
258
# File 'lib/all/io.rb', line 252

def await_writable(opts = {})
  io_selector = Concurrently::EventLoop.current.io_selector
  io_selector.await_writer(self, Concurrently::Evaluation.current)
  await_resume! opts
ensure
  io_selector.cancel_writer(self)
end