Вы находитесь на странице: 1из 22

Coro. Intro.

Evgeniy Vansevich
https://github.com/kadavr
evgeniy@just4i.ru
What is Coro?
Cooperative Threads.
Coroutine, , -
,
,

.
Coro
Coro::State,
Coro.
Cooperative Threads.
Cooperative Threads.
use Coro;
Async -
async {
print "async 1\n";
cede;
print "async 2\n";
};
print "main 1\n";
cede; Main
print "main 2\n";
cede;
Cooperative Threads.
use Coro;
async {
print "async 1\n";
Cede, yield
cede;
print "async 2\n";
};
print "main 1\n";
cede; Main
print "main 2\n";
cede;
Cooperative Threads.
cede
schedulle.
schedulle ,
""
.
, -
$Coro::idle.
Deadlock.
Deadlock - ,


,
.
Coro ,
.
$Coro::idle.
Deadlock.

use Coro;
my $wakeme = $Coro::current;
async {
$wakeme->ready if 0.5 > rand;
};
schedule;
Deadlock.

FATAL: deadlock detected.


PID SC RSS USES Description Where
31976480 -C 19k 0 [main::] [program:9]
32223768 UC 12k 1 [Coro.pm:691]
32225088 -- 2068 1 [coro manager] [Coro.pm:691]
32225184 N- 216 0 [unblock_sub scheduler] -
Channel.
Channel,

.
Coro
Coro::Channel,
Coro::Semaphore
Channel.
Channel.
use Coro;
my $chan = new Coro::Channel 2;
2
# $chan
async {

while(my $val = $chan->get){
warn "chan out:" . $val;
}
};
$chan->put($_) for(1..3);
The Real World!
Event Loop.

use Coro;
use Coro::AnyEvent;
async {
Coro::AnyEvent::sleep 4;
warn "sleep 4";
};
Coro::AnyEvent::sleep 5;
warn "sleep 5";
Event Loop.
Event Loop.
AnyEvent - the DBI of event loop.
Coro::Socket non-blocking socket-I/O.
Coro::AIO truly asynchronous file and
directory I/O.
Coro::Signal - thread signals.
Coro::Semaphore - counting semaphores.
Coro::LWP non-blocking LWP.
AnyEvent::HTTP
http_get "http://mail.ru",
rouse_cb;
my ($data, $hdr) = rouse_wait;

return undef if $hdr->{Status} =~ m/^2/;
#

AnyEvent
my $int_w = AnyEvent->signal (
signal => "INT",
cb => Coro::rouse_cb );
Coro::rouse_wait;
# .
Coro::Generator
Generator,

,
(
) ,

.
Coro::Generator

use Coro::Generator; # import 'generator' and 'yield'


my $even = generator {
my $x = 0;
while(1)
{
$x += 2;
yield yield

$x;
}
};
# This will print even numbers from 2..20
for(1..10) {
print $even->() . "\n";
}
Coroutine - wikipedia:
Deadlock - wikipedia:

Generator - wikipedia:

Coro - metacpan: Coro

Coro asynchronous - slideshare


The end.