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 { ... }
io_buffer.c
View on GitHub ↗
VALUE
rb_io_buffer_locked(VALUE self)
{
struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
// Only yield the block for a currently valid view. In particular, an
// invalid slice should not lock its source.
io_buffer_validate_for_reading(buffer);
io_buffer_lock(buffer);
return rb_ensure(rb_yield, self, rb_io_buffer_locked_ensure, self);
}
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