ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-Fork-RPC/RPC/Sync.pm
Revision: 1.4
Committed: Wed Apr 17 19:38:25 2013 UTC (13 years, 5 months ago) by root
Branch: MAIN
Changes since 1.3: +18 -12 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 package AnyEvent::Fork::RPC::Sync;
2    
3     use common::sense; # actually required to avoid spurious warnings...
4    
5 root 1.4 # declare only
6     sub AnyEvent::Fork::RPC::event;
7 root 1.1
8     sub main::test {#d#
9 root 1.4 # AnyEvent::Fork::RPC::event($_[0],$_) for 1..$_[0];
10     "3"
11 root 1.1 }
12    
13 root 1.4 our $master;
14    
15 root 1.1 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 root 1.4 sub rlen($) { ($_[0] < 384 ? 512 + 16 : 2 << int +(log $_[0] + 512) / log 2) - $_[0] - 16 }
29 root 1.2
30 root 1.1 # the goal here is to keep this simple, small and efficient
31     sub run {
32 root 1.4 my ($function, $init, $serialiser) = splice @_, -3, 3,;
33    
34 root 1.1 $master = shift;
35    
36     {
37     package main;
38     &$init if length $init;
39     $function = \&$function; # resolve function early for extra speed
40     }
41    
42 root 1.4 my ($f, $t) = eval $serialiser; die $@ if $@;
43 root 1.1
44 root 1.4 *AnyEvent::Fork::RPC::event = sub {
45     xwrite pack "L/a*", $f->(@_, 1);
46     };
47    
48     my ($rlen, $rbuf) = 512 - 16;
49 root 1.1
50 root 1.2 # the read length here is not optimal, but since we re-use $rbuf,
51     # its allocated size should eventually auto-adjust.
52 root 1.4 while (sysread $master, $rbuf, $rlen - length $rbuf, length $rbuf) {
53     $rlen = $rlen * 2 + 16 if $rlen - 128 < length $rbuf;
54    
55 root 1.2 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 root 1.1
62 root 1.2 xwrite pack "L/a*", $f->($function->(@r), "");
63     }
64 root 1.1 }
65    
66     shutdown $master, 1;
67     }
68    
69     1
70