简体   繁体   中英

Running perl subroutine in parallel with Coro

I have a subroutine which I would like to execute in parallel with Coro :

use strict;
use warnings;
use Coro;

sub mysub {
    my ($in) = @_;
    print "$in \n";
    foreach my $i (0..100000000){
    $i=$i+1;
    }
    return 1;
}

from the Coro intro I read how I can create threads:

for ( 
    ( async{ mysub "A"  }   ),
    ( async{ mysub "B"  }   ),
    ( async{ mysub "C"  }   ),
    ( async{ mysub "X"  }   ),
    ( async{ mysub "Y"  }   )
    ) {
    $_->join;
}

However, threads are created but how can I run them all in parallel? The example states that Coro::Socket (or better AnyEvent::Socket ) makes parallel execution possible but how can I make this work in my simple example?

Also (but this is a second question), why does in the above for-loop the arguments to mysub get passed but not in the example below?

my @letters = ("A", "B", "C", "X", "Y");
my @in = map { (async {mysub $_ }) } @letters;
for ( @in ) {$_->join};

Coro is a co-operative multitasking system. A thread will only cede the CPU to another when the program explicitly does so, or when it's blocked waiting for an event in a Coro-aware call.

For example, the following will wait for HTTP responses on parallel:

use Coro                          qw( async );
use LWP::Protocol::AnyEvent::http qw( );
use LWP::UserAgent                qw( );

...

for my $url (@urls) {
    async { process( $ua->get($url) ) };
}

...

Coro is powerless to split arithmetic among CPUs as your example attempts to do since it doesn't create any OS threads.

Coro does not run the coroutines in parallel, only asynchronous. See documentation:

...They are similar to kernel threads but don't (in general) run in parallel at the same time even on SMP machine..

Instead it will switch between "threads" at usually blocking points, like read, write etc, but there will be only one "thread" running at a specific time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM