How to run concurrent threads in perl? How to run concurrent threads in perl? multithreading multithreading

How to run concurrent threads in perl?


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 listof all non-joined, non-detachedthreads 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 arestill 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)


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();}


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.