Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re^2: Perl thread/semaphore

by password (Sexton)
on May 03, 2011 at 22:47 UTC ( #902777=note: print w/replies, xml ) Need Help??

in reply to Re: Perl thread/semaphore
in thread Perl thread/semaphore

Dear oshalla, thank you for your codes, it really helped me to grasp several ideas about threading in Perl. My only addition would be that's in your 1st and 2nd examples you clone the arguments (@array) in the first two cycles, meaning you're creating two threads with the same arguments: for (1..2) - in the 1st example and while ($c) - where $c=2 - in the 2nd example To fix that I used a new variable to count dispatched threads.
#!/usr/bin/perl use strict ; use warnings ; use threads ; use Thread::Queue ; my @array = qw(a b c d e f g h); my @results; my $finished_queue = new Thread::Queue ; my $c = 5 ; # Number active at once my $n = 10 ; # Total number to dispatch my $m = $n ; # Number to collect my $d = 0; #count created threads while ($n) { while ($m) { $d++; my $child = threads->create(\&sub_thread, @array) ; my $tid;my $childa; if ($d == $c) { $tid = $finished_queue->dequeue() ; $childa = threads->object($tid) ; push @results, $childa->join() ; $d--; $n--; } $m-- ; } if (!$m) { my $tid = $finished_queue->dequeue() ; my $childa = threads->object($tid) ; push @results, $childa->join() ; $n--; } } sub sub_thread { my (@temp) = (@_) ; my $tid = threads->tid() ; print "child $tid: @temp\n" ; sleep(rand(2)+2) ; $finished_queue->enqueue($tid) ; print "child $tid: finished\n" ; return "whatever from child $tid" ; } ; exit;
It's not elegant, but it works and all I needed was a quick fix. P.S. It's an old thread, but it was the most useful for me just now, so I'd rather share the solution in this old thread.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://902777]
[thepkd]: Yes this is my first time in cb. Trying to work my way around.
[JohnCub]: "A ref too far" would make a good title for anyone's perl memoirs
[thepkd]: Anyways it works with $aohoaoh[0]->{'foo '}[0]->{'bar'}
[GotToBTru]: "I did it my $way"
[JohnCub]: I hope $way isn't a hashref. ;)
[GotToBTru]: many times i've been told I made a real hash of thiings
[GotToBTru]: so .. perhaps it should b e

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (10)
As of 2016-12-06 13:48 GMT
Find Nodes?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:

    Results (105 votes). Check out past polls.