Skip to content

Commit b8b0ab1

Browse files
committed
blocking ring buffer now uses a ring buffer
1 parent 774c213 commit b8b0ab1

File tree

1 file changed

+10
-15
lines changed

1 file changed

+10
-15
lines changed

lib/concurrent/channel/blocking_ring_buffer.rb

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,63 +2,58 @@ module Concurrent
22
class BlockingRingBuffer
33

44
def initialize(capacity)
5-
@buffer = Array.new(capacity)
5+
@buffer = RingBuffer.new(capacity)
66
@first = @last = 0
77
@count = 0
88
@mutex = Mutex.new
99
@condition = Condition.new
1010
end
1111

1212
def capacity
13-
@mutex.synchronize { @buffer.size }
13+
@mutex.synchronize { @buffer.capacity }
1414
end
1515

1616
def count
17-
@mutex.synchronize { @count }
17+
@mutex.synchronize { @buffer.count }
1818
end
1919

2020
def full?
21-
@mutex.synchronize { @count == @buffer.size }
21+
@mutex.synchronize { @buffer.full? }
2222
end
2323

2424
def empty?
25-
@mutex.synchronize { @count == 0 }
25+
@mutex.synchronize { @buffer.empty? }
2626
end
2727

2828
def put(value)
2929
@mutex.synchronize do
3030
wait_while_full
31-
@buffer[@last] = value
32-
@last = (@last + 1) % @buffer.size
33-
@count += 1
31+
@buffer.offer(value)
3432
@condition.signal
3533
end
3634
end
3735

3836
def take
3937
@mutex.synchronize do
4038
wait_while_empty
41-
result = @buffer[@first]
42-
@buffer[@first] = nil
43-
@first = (@first + 1) % @buffer.size
44-
@count -= 1
39+
result = @buffer.poll
4540
@condition.signal
4641
result
4742
end
4843
end
4944

5045
def peek
51-
@mutex.synchronize { @buffer[@first] }
46+
@mutex.synchronize { @buffer.peek }
5247
end
5348

5449
private
5550

5651
def wait_while_full
57-
@condition.wait(@mutex) while @count == @buffer.size
52+
@condition.wait(@mutex) while @buffer.full?
5853
end
5954

6055
def wait_while_empty
61-
@condition.wait(@mutex) while @count == 0
56+
@condition.wait(@mutex) while @buffer.empty?
6257
end
6358

6459
end

0 commit comments

Comments
 (0)