in reply to Circular buffer
For fun, I wrote one.
package Data::CircularBuffer; use strict; use warnings; # This does nothing if 'use threads;' wasn't previously executed. use threads::shared qw( bless ); sub new { my ($class, $n) = @_; ++$n; # Used to differentiate full from empty. return bless({ size => $n, buf => [ (undef) x $n ], head => 0, tail => 0, }, $class); } sub is_empty { my ($self) = @_; return $self->{head} == $self->{tail}; } # Returns empty list if the buffer is empty. That means the # following will work even if the buffer contains false elements: # while (my ($element) = $cb->shift()) { ... } sub shift { my ($self) = @_; return () if $self->is_empty(); my $val = $self->{buf}[ $self->{head} ]; $self->{buf}[ $self->{head} ] = undef; $self->{head} = ( $self->{head} + 1 ) % $self->{size}; return $val; } # Returns number of items successfully inserted. sub push { my $self = shift; my $inserted = 0; for (@_) { my $new_tail = ( $self->{tail} + 1 ) % $self->{size}; last if $new_tail == $self->{head}; $self->{buf}[ $self->{tail} ] = $_; $self->{tail} = $new_tail; } return $inserted; } 1;
Untested. Should work with a writer in one thread and a reader in another thread without locks.
Update: Now clears elements that have been shifted out of the buffer to ensure timely destruction.
|
|---|