Skip to content

Instantly share code, notes, and snippets.

@marat-chardymov
Created December 20, 2019 22:56
Show Gist options
  • Save marat-chardymov/06ef318a5e0ab9d0e7cd8043949fca76 to your computer and use it in GitHub Desktop.
Save marat-chardymov/06ef318a5e0ab9d0e7cd8043949fca76 to your computer and use it in GitHub Desktop.
presumably thread safe ring buffer
module My
class RingBuffer
def initialize(size)
@size = size
@pointer = 0
@buffer = Array.new
@mutex = Mutex.new
end
def push(value)
@mutex.synchronize do
@buffer[@pointer%@size] = value
@pointer+= 1
value
end
end
alias :<< :push
def next
@mutex.synchronize do
value = @buffer[@pointer % @size]
@pointer += 1
value
end
end
end
end
mrb = My::RingBuffer.new(3)
mrb<<1
mrb<<2
mrb<<3
mrb.next # =>1
mrb.next # =>2
mrb.next # =>3
mrb.next # =>1
mrb.next # =>2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment