| 1 |
package AnyEvent::Fork::RPC::Sync; |
| 2 |
|
| 3 |
use common::sense; # actually required to avoid spurious warnings... |
| 4 |
|
| 5 |
# declare only |
| 6 |
sub AnyEvent::Fork::RPC::event; |
| 7 |
|
| 8 |
sub main::test {#d# |
| 9 |
# AnyEvent::Fork::RPC::event($_[0],$_) for 1..$_[0]; |
| 10 |
"3" |
| 11 |
} |
| 12 |
|
| 13 |
our $master; |
| 14 |
|
| 15 |
sub xwrite($) { |
| 16 |
my $got = syswrite $master, $_[0]; |
| 17 |
|
| 18 |
while ($got < length $_[0]) { |
| 19 |
my $len = syswrite $master, $_[0], 1<<30, $got; |
| 20 |
|
| 21 |
defined $len |
| 22 |
or die "AnyEvent::Fork::RPC::Sync: write error ($!), parent gone?"; |
| 23 |
|
| 24 |
$got += $len; |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
sub rlen($) { ($_[0] < 384 ? 512 + 16 : 2 << int +(log $_[0] + 512) / log 2) - $_[0] - 16 } |
| 29 |
|
| 30 |
# the goal here is to keep this simple, small and efficient |
| 31 |
sub run { |
| 32 |
my ($function, $init, $serialiser) = splice @_, -3, 3,; |
| 33 |
|
| 34 |
$master = shift; |
| 35 |
|
| 36 |
{ |
| 37 |
package main; |
| 38 |
&$init if length $init; |
| 39 |
$function = \&$function; # resolve function early for extra speed |
| 40 |
} |
| 41 |
|
| 42 |
my ($f, $t) = eval $serialiser; die $@ if $@; |
| 43 |
|
| 44 |
*AnyEvent::Fork::RPC::event = sub { |
| 45 |
xwrite pack "L/a*", $f->(@_, 1); |
| 46 |
}; |
| 47 |
|
| 48 |
my ($rlen, $rbuf) = 512 - 16; |
| 49 |
|
| 50 |
# the read length here is not optimal, but since we re-use $rbuf, |
| 51 |
# its allocated size should eventually auto-adjust. |
| 52 |
while (sysread $master, $rbuf, $rlen - length $rbuf, length $rbuf) { |
| 53 |
$rlen = $rlen * 2 + 16 if $rlen - 128 < length $rbuf; |
| 54 |
|
| 55 |
while () { |
| 56 |
last if 5 > length $rbuf; |
| 57 |
my $len = unpack "L", $rbuf; |
| 58 |
last if 4 + $len > length $rbuf; |
| 59 |
my @r = $t->(substr $rbuf, 4, $len); |
| 60 |
substr $rbuf, 0, 4 + $len, ""; |
| 61 |
|
| 62 |
xwrite pack "L/a*", $f->($function->(@r), ""); |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
shutdown $master, 1; |
| 67 |
} |
| 68 |
|
| 69 |
1 |
| 70 |
|