ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-Fork/Fork.pm
(Generate patch)

Comparing AnyEvent-Fork/Fork.pm (file contents):
Revision 1.24 by root, Sat Apr 6 08:32:23 2013 UTC vs.
Revision 1.37 by root, Sat Apr 6 20:06:39 2013 UTC

40in whatever way you like, use some message-passing module such 40in whatever way you like, use some message-passing module such
41as L<AnyEvent::MP>, some pipe such as L<AnyEvent::ZeroMQ>, use 41as L<AnyEvent::MP>, some pipe such as L<AnyEvent::ZeroMQ>, use
42L<AnyEvent::Handle> on both sides to send e.g. JSON or Storable messages, 42L<AnyEvent::Handle> on both sides to send e.g. JSON or Storable messages,
43and so on. 43and so on.
44 44
45=head1 PROBLEM STATEMENT
46
47There are two traditional ways to implement parallel processing on UNIX
48like operating systems - fork and process, and fork+exec and process. They
49have different advantages and disadvantages that I describe below,
50together with how this module tries to mitigate the disadvantages.
51
52=over 4
53
54=item Forking from a big process can be very slow.
55
56A 5GB process needs 0.05s to fork on my 3.6GHz amd64 GNU/Linux box. This
57overhead is often shared with exec (because you have to fork first), but
58in some circumstances (e.g. when vfork is used), fork+exec can be much
59faster.
60
61This module can help here by telling a small(er) helper process to fork,
62which is faster then forking the main process, and also uses vfork where
63possible. This gives the speed of vfork, with the flexibility of fork.
64
65=item Forking usually creates a copy-on-write copy of the parent
66process.
67
68For example, modules or data files that are loaded will not use additional
69memory after a fork. When exec'ing a new process, modules and data files
70might need to be loaded again, at extra CPU and memory cost. But when
71forking, literally all data structures are copied - if the program frees
72them and replaces them by new data, the child processes will retain the
73old version even if it isn't used, which can suddenly and unexpectedly
74increase memory usage when freeing memory.
75
76The trade-off is between more sharing with fork (which can be good or
77bad), and no sharing with exec.
78
79This module allows the main program to do a controlled fork, and allows
80modules to exec processes safely at any time. When creating a custom
81process pool you can take advantage of data sharing via fork without
82risking to share large dynamic data structures that will blow up child
83memory usage.
84
85In other words, this module puts you into control over what is being
86shared and what isn't, at all times.
87
88=item Exec'ing a new perl process might be difficult.
89
90For example, it is not easy to find the correct path to the perl
91interpreter - C<$^X> might not be a perl interpreter at all.
92
93This module tries hard to identify the correct path to the perl
94interpreter. With a cooperative main program, exec'ing the interpreter
95might not even be necessary, but even without help from the main program,
96it will still work when used from a module.
97
98=item Exec'ing a new perl process might be slow, as all necessary modules
99have to be loaded from disk again, with no guarantees of success.
100
101Long running processes might run into problems when perl is upgraded
102and modules are no longer loadable because they refer to a different
103perl version, or parts of a distribution are newer than the ones already
104loaded.
105
106This module supports creating pre-initialised perl processes to be used as
107a template for new processes.
108
109=item Forking might be impossible when a program is running.
110
111For example, POSIX makes it almost impossible to fork from a
112multi-threaded program while doing anything useful in the child - in
113fact, if your perl program uses POSIX threads (even indirectly via
114e.g. L<IO::AIO> or L<threads>), you cannot call fork on the perl level
115anymore without risking corruption issues on a number of operating
116systems.
117
118This module can safely fork helper processes at any time, by calling
119fork+exec in C, in a POSIX-compatible way (via L<Proc::FastSpawn>).
120
121=item Parallel processing with fork might be inconvenient or difficult
122to implement. Modules might not work in both parent and child.
123
124For example, when a program uses an event loop and creates watchers it
125becomes very hard to use the event loop from a child program, as the
126watchers already exist but are only meaningful in the parent. Worse, a
127module might want to use such a module, not knowing whether another module
128or the main program also does, leading to problems.
129
130Apart from event loops, graphical toolkits also commonly fall into the
131"unsafe module" category, or just about anything that communicates with
132the external world, such as network libraries and file I/O modules, which
133usually don't like being copied and then allowed to continue in two
134processes.
135
136With this module only the main program is allowed to create new processes
137by forking (because only the main program can know when it is still safe
138to do so) - all other processes are created via fork+exec, which makes it
139possible to use modules such as event loops or window interfaces safely.
140
141=back
142
45=head1 EXAMPLES 143=head1 EXAMPLES
46 144
47=head2 Create a single new process, tell it to run your worker function. 145=head2 Create a single new process, tell it to run your worker function.
48 146
49 AnyEvent::Fork 147 AnyEvent::Fork
54 152
55 # now $master_filehandle is connected to the 153 # now $master_filehandle is connected to the
56 # $slave_filehandle in the new process. 154 # $slave_filehandle in the new process.
57 }); 155 });
58 156
59 # MyModule::worker might look like this 157C<MyModule> might look like this:
158
159 package MyModule;
160
60 sub MyModule::worker { 161 sub worker {
61 my ($slave_filehandle) = @_; 162 my ($slave_filehandle) = @_;
62 163
63 # now $slave_filehandle is connected to the $master_filehandle 164 # now $slave_filehandle is connected to the $master_filehandle
64 # in the original prorcess. have fun! 165 # in the original prorcess. have fun!
65 } 166 }
84 } 185 }
85 186
86 # now do other things - maybe use the filehandle provided by run 187 # now do other things - maybe use the filehandle provided by run
87 # to wait for the processes to die. or whatever. 188 # to wait for the processes to die. or whatever.
88 189
89 # My::Server::run might look like this 190C<My::Server> might look like this:
90 sub My::Server::run { 191
192 package My::Server;
193
194 sub run {
91 my ($slave, $listener, $id) = @_; 195 my ($slave, $listener, $id) = @_;
92 196
93 close $slave; # we do not use the socket, so close it to save resources 197 close $slave; # we do not use the socket, so close it to save resources
94 198
95 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO, 199 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO,
99 } 203 }
100 } 204 }
101 205
102=head2 use AnyEvent::Fork as a faster fork+exec 206=head2 use AnyEvent::Fork as a faster fork+exec
103 207
104This runs /bin/echo hi, with stdout redirected to /tmp/log and stderr to 208This runs C</bin/echo hi>, with stdandard output redirected to /tmp/log
105the communications socket. It is usually faster than fork+exec, but still 209and standard error redirected to the communications socket. It is usually
106let's you prepare the environment. 210faster than fork+exec, but still lets you prepare the environment.
107 211
108 open my $output, ">/tmp/log" or die "$!"; 212 open my $output, ">/tmp/log" or die "$!";
109 213
110 AnyEvent::Fork 214 AnyEvent::Fork
111 ->new 215 ->new
123 ->send_fh ($output) 227 ->send_fh ($output)
124 ->send_arg ("/bin/echo", "hi") 228 ->send_arg ("/bin/echo", "hi")
125 ->run ("run", my $cv = AE::cv); 229 ->run ("run", my $cv = AE::cv);
126 230
127 my $stderr = $cv->recv; 231 my $stderr = $cv->recv;
128
129=head1 PROBLEM STATEMENT
130
131There are two ways to implement parallel processing on UNIX like operating
132systems - fork and process, and fork+exec and process. They have different
133advantages and disadvantages that I describe below, together with how this
134module tries to mitigate the disadvantages.
135
136=over 4
137
138=item Forking from a big process can be very slow (a 5GB process needs
1390.05s to fork on my 3.6GHz amd64 GNU/Linux box for example). This overhead
140is often shared with exec (because you have to fork first), but in some
141circumstances (e.g. when vfork is used), fork+exec can be much faster.
142
143This module can help here by telling a small(er) helper process to fork,
144or fork+exec instead.
145
146=item Forking usually creates a copy-on-write copy of the parent
147process. Memory (for example, modules or data files that have been
148will not take additional memory). When exec'ing a new process, modules
149and data files might need to be loaded again, at extra CPU and memory
150cost. Likewise when forking, all data structures are copied as well - if
151the program frees them and replaces them by new data, the child processes
152will retain the memory even if it isn't used.
153
154This module allows the main program to do a controlled fork, and allows
155modules to exec processes safely at any time. When creating a custom
156process pool you can take advantage of data sharing via fork without
157risking to share large dynamic data structures that will blow up child
158memory usage.
159
160=item Exec'ing a new perl process might be difficult and slow. For
161example, it is not easy to find the correct path to the perl interpreter,
162and all modules have to be loaded from disk again. Long running processes
163might run into problems when perl is upgraded for example.
164
165This module supports creating pre-initialised perl processes to be used
166as template, and also tries hard to identify the correct path to the perl
167interpreter. With a cooperative main program, exec'ing the interpreter
168might not even be necessary.
169
170=item Forking might be impossible when a program is running. For example,
171POSIX makes it almost impossible to fork from a multi-threaded program and
172do anything useful in the child - strictly speaking, if your perl program
173uses posix threads (even indirectly via e.g. L<IO::AIO> or L<threads>),
174you cannot call fork on the perl level anymore, at all.
175
176This module can safely fork helper processes at any time, by calling
177fork+exec in C, in a POSIX-compatible way.
178
179=item Parallel processing with fork might be inconvenient or difficult
180to implement. For example, when a program uses an event loop and creates
181watchers it becomes very hard to use the event loop from a child
182program, as the watchers already exist but are only meaningful in the
183parent. Worse, a module might want to use such a system, not knowing
184whether another module or the main program also does, leading to problems.
185
186This module only lets the main program create pools by forking (because
187only the main program can know when it is still safe to do so) - all other
188pools are created by fork+exec, after which such modules can again be
189loaded.
190
191=back
192 232
193=head1 CONCEPTS 233=head1 CONCEPTS
194 234
195This module can create new processes either by executing a new perl 235This module can create new processes either by executing a new perl
196process, or by forking from an existing "template" process. 236process, or by forking from an existing "template" process.
275 my ($fork_fh) = @_; 315 my ($fork_fh) = @_;
276 }); 316 });
277 317
278=back 318=back
279 319
280=head1 FUNCTIONS 320=head1 THE C<AnyEvent::Fork> CLASS
321
322This module exports nothing, and only implements a single class -
323C<AnyEvent::Fork>.
324
325There are two class constructors that both create new processes - C<new>
326and C<new_exec>. The C<fork> method creates a new process by forking an
327existing one and could be considered a third constructor.
328
329Most of the remaining methods deal with preparing the new process, by
330loading code, evaluating code and sending data to the new process. They
331usually return the process object, so you can chain method calls.
332
333If a process object is destroyed before calling its C<run> method, then
334the process simply exits. After C<run> is called, all responsibility is
335passed to the specified function.
336
337As long as there is any outstanding work to be done, process objects
338resist being destroyed, so there is no reason to store them unless you
339need them later - configure and forget works just fine.
281 340
282=over 4 341=over 4
283 342
284=cut 343=cut
285 344
295use IO::FDPass; 354use IO::FDPass;
296 355
297our $VERSION = 0.5; 356our $VERSION = 0.5;
298 357
299our $PERL; # the path to the perl interpreter, deduces with various forms of magic 358our $PERL; # the path to the perl interpreter, deduces with various forms of magic
300
301=item my $pool = new AnyEvent::Fork key => value...
302
303Create a new process pool. The following named parameters are supported:
304 359
305=over 4 360=over 4
306 361
307=back 362=back
308 363
404Create a new "empty" perl interpreter process and returns its process 459Create a new "empty" perl interpreter process and returns its process
405object for further manipulation. 460object for further manipulation.
406 461
407The new process is forked from a template process that is kept around 462The new process is forked from a template process that is kept around
408for this purpose. When it doesn't exist yet, it is created by a call to 463for this purpose. When it doesn't exist yet, it is created by a call to
409C<new_exec> and kept around for future calls. 464C<new_exec> first and then stays around for future calls.
410
411When the process object is destroyed, it will release the file handle
412that connects it with the new process. When the new process has not yet
413called C<run>, then the process will exit. Otherwise, what happens depends
414entirely on the code that is executed.
415 465
416=cut 466=cut
417 467
418sub new { 468sub new {
419 my $class = shift; 469 my $class = shift;
509} 559}
510 560
511=item $pid = $proc->pid 561=item $pid = $proc->pid
512 562
513Returns the process id of the process I<iff it is a direct child of the 563Returns the process id of the process I<iff it is a direct child of the
514process> running AnyEvent::Fork, and C<undef> otherwise. 564process running AnyEvent::Fork>, and C<undef> otherwise.
515 565
516Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and 566Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and
517L<AnyEvent::Fork::Template> are direct children, and you are responsible 567L<AnyEvent::Fork::Template> are direct children, and you are responsible
518to clean up their zombies when they die. 568to clean up their zombies when they die.
519 569
520All other processes are not direct children, and will be cleaned up by 570All other processes are not direct children, and will be cleaned up by
521AnyEvent::Fork. 571AnyEvent::Fork itself.
522 572
523=cut 573=cut
524 574
525sub pid { 575sub pid {
526 $_[0][0] 576 $_[0][0]
537 587
538The code will usually be executed after this call returns, and there is no 588The code will usually be executed after this call returns, and there is no
539way to pass anything back to the calling process. Any evaluation errors 589way to pass anything back to the calling process. Any evaluation errors
540will be reported to stderr and cause the process to exit. 590will be reported to stderr and cause the process to exit.
541 591
542If you want to execute some code to take over the process (see the 592If you want to execute some code (that isn't in a module) to take over the
543"fork+exec" example in the SYNOPSIS), you should compile a function via 593process, you should compile a function via C<eval> first, and then call
544C<eval> first, and then call it via C<run>. This also gives you access to 594it via C<run>. This also gives you access to any arguments passed via the
545any arguments passed via the C<send_xxx> methods, such as file handles. 595C<send_xxx> methods, such as file handles. See the L<use AnyEvent::Fork as
596a faster fork+exec> example to see it in action.
546 597
547Returns the process object for easy chaining of method calls. 598Returns the process object for easy chaining of method calls.
548 599
549=cut 600=cut
550 601
576=item $proc = $proc->send_fh ($handle, ...) 627=item $proc = $proc->send_fh ($handle, ...)
577 628
578Send one or more file handles (I<not> file descriptors) to the process, 629Send one or more file handles (I<not> file descriptors) to the process,
579to prepare a call to C<run>. 630to prepare a call to C<run>.
580 631
581The process object keeps a reference to the handles until this is done, 632The process object keeps a reference to the handles until they have
582so you must not explicitly close the handles. This is most easily 633been passed over to the process, so you must not explicitly close the
583accomplished by simply not storing the file handles anywhere after passing 634handles. This is most easily accomplished by simply not storing the file
584them to this method. 635handles anywhere after passing them to this method - when AnyEvent::Fork
636is finished using them, perl will automatically close them.
585 637
586Returns the process object for easy chaining of method calls. 638Returns the process object for easy chaining of method calls.
587 639
588Example: pass a file handle to a process, and release it without 640Example: pass a file handle to a process, and release it without
589closing. It will be closed automatically when it is no longer used. 641closing. It will be closed automatically when it is no longer used.
605} 657}
606 658
607=item $proc = $proc->send_arg ($string, ...) 659=item $proc = $proc->send_arg ($string, ...)
608 660
609Send one or more argument strings to the process, to prepare a call to 661Send one or more argument strings to the process, to prepare a call to
610C<run>. The strings can be any octet string. 662C<run>. The strings can be any octet strings.
611 663
612The protocol is optimised to pass a moderate number of relatively short 664The protocol is optimised to pass a moderate number of relatively short
613strings - while you can pass up to 4GB of data in one go, this is more 665strings - while you can pass up to 4GB of data in one go, this is more
614meant to pass some ID information or other startup info, not big chunks of 666meant to pass some ID information or other startup info, not big chunks of
615data. 667data.
631Enter the function specified by the function name in C<$func> in the 683Enter the function specified by the function name in C<$func> in the
632process. The function is called with the communication socket as first 684process. The function is called with the communication socket as first
633argument, followed by all file handles and string arguments sent earlier 685argument, followed by all file handles and string arguments sent earlier
634via C<send_fh> and C<send_arg> methods, in the order they were called. 686via C<send_fh> and C<send_arg> methods, in the order they were called.
635 687
688The process object becomes unusable on return from this function - any
689further method calls result in undefined behaviour.
690
636The function name should be fully qualified, but if it isn't, it will be 691The function name should be fully qualified, but if it isn't, it will be
637looked up in the main package. 692looked up in the C<main> package.
638 693
639If the called function returns, doesn't exist, or any error occurs, the 694If the called function returns, doesn't exist, or any error occurs, the
640process exits. 695process exits.
641 696
642Preparing the process is done in the background - when all commands have 697Preparing the process is done in the background - when all commands have
643been sent, the callback is invoked with the local communications socket 698been sent, the callback is invoked with the local communications socket
644as argument. At this point you can start using the socket in any way you 699as argument. At this point you can start using the socket in any way you
645like. 700like.
646
647The process object becomes unusable on return from this function - any
648further method calls result in undefined behaviour.
649 701
650If the communication socket isn't used, it should be closed on both sides, 702If the communication socket isn't used, it should be closed on both sides,
651to save on kernel memory. 703to save on kernel memory.
652 704
653The socket is non-blocking in the parent, and blocking in the newly 705The socket is non-blocking in the parent, and blocking in the newly
728 479 vfork+execs per second, using AnyEvent::Fork->new_exec 780 479 vfork+execs per second, using AnyEvent::Fork->new_exec
729 781
730So how can C<< AnyEvent->new >> be faster than a standard fork, even 782So how can C<< AnyEvent->new >> be faster than a standard fork, even
731though it uses the same operations, but adds a lot of overhead? 783though it uses the same operations, but adds a lot of overhead?
732 784
733The difference is simply the process size: forking the 6MB process takes 785The difference is simply the process size: forking the 5MB process takes
734so much longer than forking the 2.5MB template process that the overhead 786so much longer than forking the 2.5MB template process that the extra
735introduced is canceled out. 787overhead introduced is canceled out.
736 788
737If the benchmark process grows, the normal fork becomes even slower: 789If the benchmark process grows, the normal fork becomes even slower:
738 790
739 1340 new processes, manual fork in a 20MB process 791 1340 new processes, manual fork of a 20MB process
740 731 new processes, manual fork in a 200MB process 792 731 new processes, manual fork of a 200MB process
741 235 new processes, manual fork in a 2000MB process 793 235 new processes, manual fork of a 2000MB process
742 794
743What that means (to me) is that I can use this module without having a 795What that means (to me) is that I can use this module without having a bad
744very bad conscience because of the extra overhead required to start new 796conscience because of the extra overhead required to start new processes.
745processes.
746 797
747=head1 TYPICAL PROBLEMS 798=head1 TYPICAL PROBLEMS
748 799
749This section lists typical problems that remain. I hope by recognising 800This section lists typical problems that remain. I hope by recognising
750them, most can be avoided. 801them, most can be avoided.
751 802
752=over 4 803=over 4
753 804
754=item "leaked" file descriptors for exec'ed processes 805=item leaked file descriptors for exec'ed processes
755 806
756POSIX systems inherit file descriptors by default when exec'ing a new 807POSIX systems inherit file descriptors by default when exec'ing a new
757process. While perl itself laudably sets the close-on-exec flags on new 808process. While perl itself laudably sets the close-on-exec flags on new
758file handles, most C libraries don't care, and even if all cared, it's 809file handles, most C libraries don't care, and even if all cared, it's
759often not possible to set the flag in a race-free manner. 810often not possible to set the flag in a race-free manner.
779libraries or the code that leaks those file descriptors. 830libraries or the code that leaks those file descriptors.
780 831
781Fortunately, most of these leaked descriptors do no harm, other than 832Fortunately, most of these leaked descriptors do no harm, other than
782sitting on some resources. 833sitting on some resources.
783 834
784=item "leaked" file descriptors for fork'ed processes 835=item leaked file descriptors for fork'ed processes
785 836
786Normally, L<AnyEvent::Fork> does start new processes by exec'ing them, 837Normally, L<AnyEvent::Fork> does start new processes by exec'ing them,
787which closes file descriptors not marked for being inherited. 838which closes file descriptors not marked for being inherited.
788 839
789However, L<AnyEvent::Fork::Early> and L<AnyEvent::Fork::Template> offer 840However, L<AnyEvent::Fork::Early> and L<AnyEvent::Fork::Template> offer
798 849
799The solution is to either not load these modules before use'ing 850The solution is to either not load these modules before use'ing
800L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay 851L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay
801initialising them, for example, by calling C<init Gtk2> manually. 852initialising them, for example, by calling C<init Gtk2> manually.
802 853
803=item exit runs destructors 854=item exiting calls object destructors
804 855
805This only applies to users of Lc<AnyEvent::Fork:Early> and 856This only applies to users of Lc<AnyEvent::Fork:Early> and
806L<AnyEvent::Fork::Template>. 857L<AnyEvent::Fork::Template>.
807 858
808When a process created by AnyEvent::Fork exits, it might do so by calling 859When a process created by AnyEvent::Fork exits, it might do so by calling
830to make it so, mostly due to the bloody broken perl that nobody seems to 881to make it so, mostly due to the bloody broken perl that nobody seems to
831care about. The fork emulation is a bad joke - I have yet to see something 882care about. The fork emulation is a bad joke - I have yet to see something
832useful that you can do with it without running into memory corruption 883useful that you can do with it without running into memory corruption
833issues or other braindamage. Hrrrr. 884issues or other braindamage. Hrrrr.
834 885
835Cygwin perl is not supported at the moment, as it should implement fd 886Cygwin perl is not supported at the moment due to some hilarious
836passing, but doesn't, and rolling my own is hard, as cygwin doesn't 887shortcomings of its API - see L<IO::FDPoll> for more details.
837support enough functionality to do it.
838 888
839=head1 SEE ALSO 889=head1 SEE ALSO
840 890
841L<AnyEvent::Fork::Early> (to avoid executing a perl interpreter), 891L<AnyEvent::Fork::Early> (to avoid executing a perl interpreter),
842L<AnyEvent::Fork::Template> (to create a process by forking the main 892L<AnyEvent::Fork::Template> (to create a process by forking the main

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines