views:

105

answers:

4

The following does not appear to run in concurrent threads as I expected, but rather each process blocks until it is complete:

my @arr = (1,2,3,4);
foreach (@arr) {
   threads->new(\&doSomething, $_)->join;
}

sub doSomething {
    my $thread = shift;
    print "thread $thread\n";
    sleep(5);
}

In other words, it appears to be executing the same as the non-threaded version would:

my @arr = (1,2,3,4);
foreach (@arr) {
   doSomething($_);
}

I am running ActivePerl v5.10.1 mswin32-x86-multi-thread

How to I run concurrent threads in perl?

+6  A: 

See perldoc threads.

The problem is that calling join() on a thread waits for it to finish. You want to spawn threads and then join after, not spawn/join as one operation.

A further look at perldoc threads says:

threads->list()

threads->list(threads::all)

threads->list(threads::running)

threads->list(threads::joinable)

With no arguments (or using threads::all ) and in a list context, returns a list of all non-joined, non-detached threads objects. In a scalar context, returns a count of the same.

With a true argument (using threads::running), returns a list of all non-joined, non-detached threads objects that are still running.

With a false argument (using threads::joinable ), returns a list of all non-joined, non-detached threads objects that have finished running (i.e., for which ->join() will not block).

You can use this to loop and list threads, joining when possible, until all threads are complete (and you'll probably want an upper limit to wait time where you will kill them and abort)

Daenyth
i have tried this - just spawning at once, then iterating through the threads and joining, but as soon as the first join is called, it blocks. it's almost as if I need to yield until each thread is complete, then join, but I'm not quite sure how to do that
Exactly. `join` is a blocking operation. But threads that have already been spawned will continue to run while the main process is waiting for `join` to return. In this case, if you spawn all threads and then join, you'd expect the first join call to take about 5 seconds, and all the other join calls to be very short.
mobrule
marked as answer. list(), in combination with is_joinable was what i needed - thanks
+2  A: 

join (not only in Perl) causes calling thread to wait for another thread finish. So your example spawns thread, waits for it to finish, and then spawns another thread, so you get impression that there are no threads spawned at all.

el.pescado
how would I accomplish this then?
+5  A: 

you have to join them afterwards, not while creating them:

my @arr = (1,2,3,4);
my @threads;
foreach (@arr) {
   push @threads, threads->new(\&doSomething, $_);
}
foreach (@threads) {
   $_->join();
}
Steve Schnepp
A: 

You have to call join after spawning all threads:

perl -mthreads -le'$_->join for map threads->new(sub{print"Thread $_";sleep(2)}),1..4'
Hynek -Pichi- Vychodil