perlquestion
karlgoethebier
<p>Hi all,</p>
<p>i figured this out by RTFM:</p>
<c>
#!/usr/bin/env perl
use strict;
use warnings;
use threads;
use threads::shared;
use Thread::Semaphore;
use Math::BigInt;
use Data::Dump;
use feature qw(say);
my @numbers = ( 1 .. 10 );
my %result : shared;
my $semaphore = Thread::Semaphore->new(4);
my @threads = map {
$semaphore->down;
threads->create( \&process, $_ );
} @numbers;
$_->join for @threads;
dd \%result;
sub process {
my $number = shift;
my $factorial = factorial($number);
say qq($number $factorial);
eval { $result{$number} = $factorial; };
say $@ if $@;
$semaphore->up;
}
sub factorial {
my $number = shift;
Math::BigInt->bfac($number);
}
__END__
karls-mac-mini:monks karl $ ./semaphore.pl
...
10 3628800
Invalid value for shared scalar at ./semaphore.pl line 29.
...
</c>
<p>It works, but the only thing i couldn't manage is to assign the results to a hash.</p>
<p>I did some more RTFM about how to accomplish this but without success.</p>
<p>What do i miss?</p>
<p>Thank you very much for any hint and best regards,</p>
<p>Karl</p>
<p>P.S.: I asked something similar at noon it the CB and posted an example in my scratchpad. [Corion] kindly advised my not to use [mod://Thread::Semaphore] and pointed me to the canonical advice given by [BrowserUK] which uses [mod://Thread::Queue]. But i couldn't resist to use Thread::Semaphore</p>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-1001958">
<p>«The Crux of the Biscuit is the Apostrophe»</p>
</div></div>