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?
Best Answer
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: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)