develooper Front page | perl.perl6.users | Postings from October 2017

Nice Channel and thread example

Thread Next
From:
Norman Gaywood
Date:
October 30, 2017 05:58
Subject:
Nice Channel and thread example
Message ID:
CAHJ-_U5LPorSqYnS7oH=3Ab_fq=EF5c0OzfDr7A76ip=BuiL2g@mail.gmail.com
Looking at Andrew Shitov's new "Using Perl6" book and was playing around
with his "94. Parallel file processing" and came up with the following (I
think nice) example.

# There is a thread to populate $dir-channel by reading filenames in a
directory with dir()
# and $N worker threads to read the filenames from the $dir-channel.

use v6;

sub MAIN( $dir = ".", :$N = 4 ) {

    my $dir-channel = Channel.new();
    my $dir-read = start {
        $dir-channel.send( $_ ) for dir $dir;
        close $dir-channel;
    }

    my @workers = (^$N).map: {
        start {
            while my $file = $dir-channel.receive() {
                say $file.path;
            }
            CATCH {
                when X::Channel::ReceiveOnClosed { .resume }
            }
        }
    }

    await $dir-read, @workers;
}


-- 
Norman Gaywood, Computer Systems Officer
School of Science and Technology
University of New England
Armidale NSW 2351, Australia

ngaywood@une.edu.au  http://turing.une.edu.au/~ngaywood
Phone: +61 (0)2 6773 2412  Mobile: +61 (0)4 7862 0062

Please avoid sending me Word or Power Point attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About