in reply to Threading and join/termination question

I'm not sure what you are tring to do, but your second example has
my @results :shared = 1;
which adds an unneccesary element to the array. It should be:
my @results :shared;

This seems to work right for me. Remember, it's up to the system as to which thread gets run first, unless you prioritize them. So run the code below multiple times, and see how the system sometimes gets the order right, but will sometimes lets a different thread order. Also you should lock @results

#!/usr/bin/perl -w use strict; use threads; use threads::shared; use Thread::Semaphore; my $sem = Thread::Semaphore->new(15); # max 15 threads my @results:shared; for my $i (0..5) { $sem->down; my $t = threads->create(\&mySubName, $i); } <>; print join(" ",@results); <>; sub mySubName { threads->detach(); my $foo = shift(@_); print "$foo\n"; lock @results; push (@results,$foo); $sem->up; }

I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku ................... flash japh

Replies are listed 'Best First'.
Re^2: Threading and join/termination question
by cormanaz (Deacon) on Jul 31, 2014 at 18:57 UTC
    Thanks for the reply. Yes I discovered that mistake. Thought the "= 1" was a flag or something.

    Anyway when I ran this, I still only got 0 1 2 3 in the last line of output, so it was missing 4 and 5. Thinking maybe the script was terminating before the threads finished, I tried adding

    while (threads->list()) { sleep 1; }
    after the for loop. That took care of it. Interestingly, I first tried .1 for the sleep argument and only got the 4. I don't understand that. Doesn't seem like a push should take that long.
      sleep doesn't handle real numbers, it takes only the int part of its argument.
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ