Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

IO::Buffer#locked

[A] () { (::IO::Buffer) -> A } -> A
locked { ... }

Prevents the buffer or its buffer source from being moved or freed while the block is executing. Locks are nested and shared with slices backed by the same buffer source. The source remains locked until every nested lock has been released.

Locking protects allocation lifetime; it does not serialize access to the bytes. Code that shares mutable buffer contents between threads must still use appropriate synchronization.

Example
buffer = IO::Buffer.new(4)
buffer.locked? #=> false

Fiber.schedule do
  buffer.locked do
    buffer.write(io) # theoretical system call interface
  end
end

Fiber.schedule do
  buffer.locked do
    buffer.set_string("test", 0) # Nested locking is allowed.
  end
end
See also #locked? #inspect #hexdump #not! also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1