Created
March 20, 2014 21:48
-
-
Save evanphx/9674625 to your computer and use it in GitHub Desktop.
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
def read(n) | |
start: | |
while true | |
offset = @buffer.current_offset | |
# If we can't update the offset, someone else did it at the same time, | |
# go again. | |
next if cas(&@buffer.current_offset, offset, offset+n) | |
# If the buffer contains all the data we need, return it! | |
if offset + n < @buffer.size | |
return buffer.buf(offset,offset+n) | |
end | |
# Otherwise grab the lock and make a new buffer | |
@resize_lock.synchronize do | |
goto start if offset + n <= @buffer.size | |
start = @buffer.buf(offset,buffer.size) | |
rest = n - (buffer.size - offset) | |
new_buffer = Buffer.new(self) | |
new_buffer.fill_at_least(rest) | |
ret = start + new_buffer.buf(0,rest) | |
new_buffer.current_offset = rest | |
@buffer = new_buffer | |
return ret | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@headius I am a little slow on the uptake here. How would the buffer and offset be mismatched in this race?
If we store a local reference to @buffer (buffer = @buffer) then we are working with the local copy's #current_offset too.