http://www.perlmonks.org?node_id=1080690


in reply to Threading Equivalent to this Parallel::ForkManager Example

Starting a whole thread just print a value is silly, but no more so than forking a process I suppose.

Notionally a direct equivalent:

#! perl -slw use strict; use threads; use threads::shared; my $sem :shared; our $MAX //= 10; my $array = 'list.txt'; open my $handle, '<', $array; chomp(my @array = <$handle>); close $handle; my @threads; for my $printme ( @array ) { push @threads, async{ lock $sem; print $printme; }; sleep 1 while threads->list( threads::running ) > $MAX; } $_->join for @threads;

A simplistic thread pool solution:

#! perl -slw use strict; use threads; use threads::shared; use Thread::Queue; our $MAX //= 10; my $sem: shared; my $Q = new Thread::Queue; sub thread { while( my $printme = $Q->dequeue ) { lock $sem; print $printme; } } my @threads = map async( \&thread ), 1 .. $MAX; my $array = 'list.txt'; open my $handle, '<', $array; chomp, $Q->enqueue( $_ ) while defined( $_ = <$handle> ); close $handle; $Q->enqueue( (undef) x $MAX ); $_->join for @threads;

(Neither tested).


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.