in reply to What is this "Do you need to predeclare croak" about? [SOLVED]
Hello karlgoethebier,
The demonstration looks fine. Some modules may not play well with threads, unfortunately. The LWP::Simple module has many dependencies. One of them may be unsafe for use with threads. In that case, the use_threads option is necessary to have workers spawn via fork on the Windows platform or when loading threads at the top of the script.
Network related tasks may benefit from MCE's interval option. It helps stagger the immediate code that follows. For this use-case, calling yield prevents workers from initiating remote connections at the same time. It is similarly to sleep, but runs serially, not parallel, for that duration of time. All participating workers wait their turn to sleep.
The next MCE update 1.830 will default to 1 for the posix_exit option. It is nearly impossible to manage a list of modules thread-safe or multi-process END safe for that matter.
#!/usr/bin/env perl # http://www.perlmonks.org/?node_id=1192821 use strict; use warnings; use MCE::Loop; use MCE::Shared; use LWP::Simple; use feature qw(say); my $result = MCE::Shared->hash; my @urls = qw(http://perlmonks.org http://www.whitehouse.org); MCE::Loop::init { max_workers => 'auto', chunk_size => 1, interval => 0.008, posix_exit => 1, use_threads => 0 }; my $fetch = sub { eval { head(shift) }; warn $@ if $@; }; mce_loop { MCE->yield; my @data = $fetch->( $_ ); $result->set( $_ => \@data ); } @urls; { no warnings qw(uninitialized); my $iter = $result->iterator(); while ( my ( $url, $data ) = $iter->() ) { say $url; say for @$data; say q(---); } }
MCE Loop is wantarray-aware. This allows one to use the gather method to send the key-value pair into a plain hash. For readers, this is how it was done before MCE::Shared came about.
#!/usr/bin/env perl # http://www.perlmonks.org/?node_id=1192821 use strict; use warnings; use MCE::Loop; use LWP::Simple; use feature qw(say); my @urls = qw(http://perlmonks.org http://www.whitehouse.org); MCE::Loop::init { max_workers => 'auto', chunk_size => 1, interval => 0.008, posix_exit => 1, use_threads => 0 }; my $fetch = sub { eval { head(shift) }; warn $@ if $@; }; my %result = mce_loop { MCE->yield; my @data = $fetch->( $_ ); MCE->gather( $_ => \@data ); } @urls; { no warnings qw(uninitialized); while ( my ( $url, $data ) = each %result ) { say $url; say for @$data; say q(---); } }
Regards, Mario
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: What is this "Do you need to predeclare croak" about?
by marioroy (Prior) on Jun 14, 2017 at 23:03 UTC | |
Re^2: What is this "Do you need to predeclare croak" about?
by karlgoethebier (Abbot) on Jun 15, 2017 at 15:58 UTC |