End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
IO::Buffer#locked
locked { ... }
io_buffer.c
View on GitHub ↗
VALUE
rb_io_buffer_locked(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
if (data->flags & RB_IO_BUFFER_LOCKED) {
rb_raise(rb_eIOBufferLockedError, "Buffer already locked!");
}
data->flags |= RB_IO_BUFFER_LOCKED;
VALUE result = rb_yield(self);
data->flags &= ~RB_IO_BUFFER_LOCKED;
return result;
}
Allows to process a buffer in exclusive way, for concurrency-safety. While the block is performed, the buffer is considered locked, and no other code can enter the lock. Also, locked buffer can’t be changed with resize or free.
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
# in `locked': Buffer already locked! (IO::Buffer::LockedError)
buffer.locked do
buffer.set_string(...)
end
end
The following operations acquire a lock: resize, free.
Locking is not thread safe. It is designed as a safety net around non-blocking system calls. You can only share a buffer between threads with appropriate synchronisation techniques.