Hi all,
i figured this out by RTFM:
#!/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.
...
It works, but the only thing i couldn't manage is to assign the results to a hash.
I did some more RTFM about how to accomplish this but without success.
What do i miss?
Thank you very much for any hint and best regards,
Karl
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 Thread::Semaphore and pointed me to the canonical advice given by BrowserUK which uses Thread::Queue. But i couldn't resist to use Thread::Semaphore
«The Crux of the Biscuit is the Apostrophe»
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|