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.


In reply to Re: Circular buffer by ikegami
in thread Circular buffer by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.