Created
December 20, 2019 22:56
-
-
Save marat-chardymov/06ef318a5e0ab9d0e7cd8043949fca76 to your computer and use it in GitHub Desktop.
presumably thread safe ring buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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