in reply to complex iterator needed

Co-routines are almost trivial with threads.

#! perl -slw use strict; use threads qw[ yield ]; use threads::shared; use Thread::Queue; my $Q = Thread::Queue->new; sub complexGenerator{ my( $max ) = @_; for( 1 .. $max ){ # Do our complex generation here # wait till they are ready for the next result select undef, undef, undef, 0.01 and yield while $Q->pending; # and let them have it $Q->enqueue( $_ ); } # Indicate we're done $Q->enqueue( undef ); } my $coro = threads->new( \&complexGenerator, 100 ); while( my $next = $Q->dequeue ) { # Process latest result set printf $next; <stdin>; } $coro->join; __END__

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Timing (and a little luck) are everything!

Replies are listed 'Best First'.
Re: Re: complex iterator needed
by japhy (Canon) on Feb 01, 2004 at 14:04 UTC
    I thought "yield" was something I might want. DAMN YOU, Ruby! DAMN YOU!
    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      It works almost as well without the yield.

      That is really a micro-optimisation, in that it relinguishes the rest of the current timeslice, giving the co-routine a chance of getting control a few cycles earlier.

      If your platform supports a sleep that handles microseconds *and* relinguishes timeslice (e.g Win32::Sleep), then the yield becomes completely redundant.


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      Timing (and a little luck) are everything!