Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run concurrent threads in perl?

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?

like image 377
user210757 Avatar asked Jun 22 '10 16:06

user210757


People also ask

How do I use multithreading in Perl?

Creating Threads Like any other module, you need to tell Perl that you want to use it; use threads; imports all the pieces you need to create basic threads. The create() method takes a reference to a subroutine and creates a new thread that starts executing in the referenced subroutine.

Can multiple threads run at once?

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.

Does Perl support concurrency?

Instead, Perl 6 offers a rich variety of composable concurrency tools such as promises, supplies, and channels, which, while not making concurrency as easy as “Hello World,” nonetheless take much of the drudgery away from writing concurrent code.

Does Perl support multithreading?

Perl can do asynchronous programming with modules like IO::Async or Coro, but it's single threaded. You can compile Perl with threads, which provide multi-threaded computing.


1 Answers

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)

like image 171
Daenyth Avatar answered Oct 06 '22 01:10

Daenyth