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

Comparing Coro/Coro.pm (file contents):
Revision 1.305 by root, Thu Aug 4 19:37:58 2011 UTC vs.
Revision 1.359 by root, Wed Jul 21 06:40:13 2021 UTC

72 72
73=over 4 73=over 4
74 74
75=item 1. Creation 75=item 1. Creation
76 76
77The first thing in the life of a coro thread is it's creation - 77The first thing in the life of a coro thread is its creation -
78obviously. The typical way to create a thread is to call the C<async 78obviously. The typical way to create a thread is to call the C<async
79BLOCK> function: 79BLOCK> function:
80 80
81 async { 81 async {
82 # thread code goes here 82 # thread code goes here
91This creates a new coro thread and puts it into the ready queue, meaning 91This creates a new coro thread and puts it into the ready queue, meaning
92it will run as soon as the CPU is free for it. 92it will run as soon as the CPU is free for it.
93 93
94C<async> will return a Coro object - you can store this for future 94C<async> will return a Coro object - you can store this for future
95reference or ignore it - a thread that is running, ready to run or waiting 95reference or ignore it - a thread that is running, ready to run or waiting
96for some event is alive on it's own. 96for some event is alive on its own.
97 97
98Another way to create a thread is to call the C<new> constructor with a 98Another way to create a thread is to call the C<new> constructor with a
99code-reference: 99code-reference:
100 100
101 new Coro sub { 101 new Coro sub {
188 188
189 my $hello_world = $coro->join; 189 my $hello_world = $coro->join;
190 190
191 print $hello_world; 191 print $hello_world;
192 192
193Another way to terminate is to call C<< Coro::terminate >>, which at any 193Another way to terminate is to call C<< Coro::terminate >>, the
194subroutine call nesting level: 194thread-equivalent of C<exit>, which works at any subroutine call nesting
195level:
195 196
196 async { 197 async {
197 Coro::terminate "return value 1", "return value 2"; 198 Coro::terminate "return value 1", "return value 2";
198 }; 199 };
199 200
200And yet another way is to C<< ->cancel >> (or C<< ->safe_cancel >>) the 201Yet another way is to C<< ->cancel >> (or C<< ->safe_cancel >>) the coro
201coro thread from another thread: 202thread from another thread:
202 203
203 my $coro = async { 204 my $coro = async {
204 exit 1; 205 exit 1;
205 }; 206 };
206 207
218So, cancelling a thread that runs in an XS event loop might not be the 219So, cancelling a thread that runs in an XS event loop might not be the
219best idea, but any other combination that deals with perl only (cancelling 220best idea, but any other combination that deals with perl only (cancelling
220when a thread is in a C<tie> method or an C<AUTOLOAD> for example) is 221when a thread is in a C<tie> method or an C<AUTOLOAD> for example) is
221safe. 222safe.
222 223
223Lastly, a coro thread object that isn't referenced is C<< ->cancel >>'ed 224Last not least, a coro thread object that isn't referenced is C<<
224automatically - just like other objects in Perl. This is not such a common 225->cancel >>'ed automatically - just like other objects in Perl. This
225case, however - a running thread is referencedy b C<$Coro::current>, a 226is not such a common case, however - a running thread is referencedy by
226thread ready to run is referenced by the ready queue, a thread waiting 227C<$Coro::current>, a thread ready to run is referenced by the ready queue,
227on a lock or semaphore is referenced by being in some wait list and so 228a thread waiting on a lock or semaphore is referenced by being in some
228on. But a thread that isn't in any of those queues gets cancelled: 229wait list and so on. But a thread that isn't in any of those queues gets
230cancelled:
229 231
230 async { 232 async {
231 schedule; # cede to other coros, don't go into the ready queue 233 schedule; # cede to other coros, don't go into the ready queue
232 }; 234 };
233 235
234 cede; 236 cede;
235 # now the async above is destroyed, as it is not referenced by anything. 237 # now the async above is destroyed, as it is not referenced by anything.
236 238
239A slightly embellished example might make it clearer:
240
241 async {
242 my $guard = Guard::guard { print "destroyed\n" };
243 schedule while 1;
244 };
245
246 cede;
247
248Superficially one might not expect any output - since the C<async>
249implements an endless loop, the C<$guard> will not be cleaned up. However,
250since the thread object returned by C<async> is not stored anywhere, the
251thread is initially referenced because it is in the ready queue, when it
252runs it is referenced by C<$Coro::current>, but when it calls C<schedule>,
253it gets C<cancel>ed causing the guard object to be destroyed (see the next
254section), and printing its message.
255
256If this seems a bit drastic, remember that this only happens when nothing
257references the thread anymore, which means there is no way to further
258execute it, ever. The only options at this point are leaking the thread,
259or cleaning it up, which brings us to...
260
237=item 5. Cleanup 261=item 5. Cleanup
238 262
239Threads will allocate various resources. Most but not all will be returned 263Threads will allocate various resources. Most but not all will be returned
240when a thread terminates, during clean-up. 264when a thread terminates, during clean-up.
241 265
242Cleanup is quite similar to throwing an uncaught exception: perl will 266Cleanup is quite similar to throwing an uncaught exception: perl will
243work it's way up through all subroutine calls and blocks. On it's way, it 267work its way up through all subroutine calls and blocks. On its way, it
244will release all C<my> variables, undo all C<local>'s and free any other 268will release all C<my> variables, undo all C<local>'s and free any other
245resources truly local to the thread. 269resources truly local to the thread.
246 270
247So, a common way to free resources is to keep them referenced only by my 271So, a common way to free resources is to keep them referenced only by my
248variables: 272variables:
259 283
260 my $sem = new Coro::Semaphore; 284 my $sem = new Coro::Semaphore;
261 285
262 async { 286 async {
263 my $lock_guard = $sem->guard; 287 my $lock_guard = $sem->guard;
264 # if we reutrn, or die or get cancelled, here, 288 # if we return, or die or get cancelled, here,
265 # then the semaphore will be "up"ed. 289 # then the semaphore will be "up"ed.
266 }; 290 };
267 291
268The C<Guard::guard> function comes in handy for any custom cleanup you 292The C<Guard::guard> function comes in handy for any custom cleanup you
269might want to do (but you cannot switch to other coroutines form those 293might want to do (but you cannot switch to other coroutines from those
270code blocks): 294code blocks):
271 295
272 async { 296 async {
273 my $window = new Gtk2::Window "toplevel"; 297 my $window = new Gtk2::Window "toplevel";
274 # The window will not be cleaned up automatically, even when $window 298 # The window will not be cleaned up automatically, even when $window
275 # gets freed, so use a guard to ensure it's destruction 299 # gets freed, so use a guard to ensure its destruction
276 # in case of an error: 300 # in case of an error:
277 my $window_guard = Guard::guard { $window->destroy }; 301 my $window_guard = Guard::guard { $window->destroy };
278 302
279 # we are safe here 303 # we are safe here
280 }; 304 };
291=item 6. Viva La Zombie Muerte 315=item 6. Viva La Zombie Muerte
292 316
293Even after a thread has terminated and cleaned up its resources, the Coro 317Even after a thread has terminated and cleaned up its resources, the Coro
294object still is there and stores the return values of the thread. 318object still is there and stores the return values of the thread.
295 319
296The means the Coro object gets freed automatically when the thread has 320When there are no other references, it will simply be cleaned up and
297terminated and cleaned up and there arenot other references. 321freed.
298 322
299If there are, the Coro object will stay around, and you can call C<< 323If there areany references, the Coro object will stay around, and you
300->join >> as many times as you wish to retrieve the result values: 324can call C<< ->join >> as many times as you wish to retrieve the result
325values:
301 326
302 async { 327 async {
303 print "hi\n"; 328 print "hi\n";
304 1 329 1
305 }; 330 };
342 367
343our $idle; # idle handler 368our $idle; # idle handler
344our $main; # main coro 369our $main; # main coro
345our $current; # current coro 370our $current; # current coro
346 371
347our $VERSION = 6.05; 372our $VERSION = 6.57;
348 373
349our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait); 374our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait);
350our %EXPORT_TAGS = ( 375our %EXPORT_TAGS = (
351 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)], 376 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)],
352); 377);
357=over 4 382=over 4
358 383
359=item $Coro::main 384=item $Coro::main
360 385
361This variable stores the Coro object that represents the main 386This variable stores the Coro object that represents the main
362program. While you cna C<ready> it and do most other things you can do to 387program. While you can C<ready> it and do most other things you can do to
363coro, it is mainly useful to compare again C<$Coro::current>, to see 388coro, it is mainly useful to compare again C<$Coro::current>, to see
364whether you are running in the main program or not. 389whether you are running in the main program or not.
365 390
366=cut 391=cut
367 392
474C<async> does. As the coro is being reused, stuff like C<on_destroy> 499C<async> does. As the coro is being reused, stuff like C<on_destroy>
475will not work in the expected way, unless you call terminate or cancel, 500will not work in the expected way, unless you call terminate or cancel,
476which somehow defeats the purpose of pooling (but is fine in the 501which somehow defeats the purpose of pooling (but is fine in the
477exceptional case). 502exceptional case).
478 503
479The priority will be reset to C<0> after each run, tracing will be 504The priority will be reset to C<0> after each run, all C<swap_sv> calls
480disabled, the description will be reset and the default output filehandle 505will be undone, tracing will be disabled, the description will be reset
481gets restored, so you can change all these. Otherwise the coro will 506and the default output filehandle gets restored, so you can change all
482be re-used "as-is": most notably if you change other per-coro global 507these. Otherwise the coro will be re-used "as-is": most notably if you
483stuff such as C<$/> you I<must needs> revert that change, which is most 508change other per-coro global stuff such as C<$/> you I<must needs> revert
484simply done by using local as in: C<< local $/ >>. 509that change, which is most simply done by using local as in: C<< local $/
510>>.
485 511
486The idle pool size is limited to C<8> idle coros (this can be 512The idle pool size is limited to C<8> idle coros (this can be
487adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle 513adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle
488coros as required. 514coros as required.
489 515
613 # at this place, the timezone is Antarctica/South_Pole, 639 # at this place, the timezone is Antarctica/South_Pole,
614 # without disturbing the TZ of any other coro. 640 # without disturbing the TZ of any other coro.
615 }; 641 };
616 642
617This can be used to localise about any resource (locale, uid, current 643This can be used to localise about any resource (locale, uid, current
618working directory etc.) to a block, despite the existance of other 644working directory etc.) to a block, despite the existence of other
619coros. 645coros.
620 646
621Another interesting example implements time-sliced multitasking using 647Another interesting example implements time-sliced multitasking using
622interval timers (this could obviously be optimised, but does the job): 648interval timers (this could obviously be optimised, but does the job):
623 649
628 Coro::on_enter { 654 Coro::on_enter {
629 # on entering the thread, we set an VTALRM handler to cede 655 # on entering the thread, we set an VTALRM handler to cede
630 $SIG{VTALRM} = sub { cede }; 656 $SIG{VTALRM} = sub { cede };
631 # and then start the interval timer 657 # and then start the interval timer
632 Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0.01, 0.01; 658 Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0.01, 0.01;
633 }; 659 };
634 Coro::on_leave { 660 Coro::on_leave {
635 # on leaving the thread, we stop the interval timer again 661 # on leaving the thread, we stop the interval timer again
636 Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0, 0; 662 Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0, 0;
637 }; 663 };
638 664
639 &{+shift}; 665 &{+shift};
640 } 666 }
641 667
642 # use like this: 668 # use like this:
643 timeslice { 669 timeslice {
644 # The following is an endless loop that would normally 670 # The following is an endless loop that would normally
645 # monopolise the process. Since it runs in a timesliced 671 # monopolise the process. Since it runs in a timesliced
646 # environment, it will regularly cede to other threads. 672 # environment, it will regularly cede to other threads.
647 while () { } 673 while () { }
648 }; 674 };
649 675
650 676
651=item killall 677=item killall
652 678
653Kills/terminates/cancels all coros except the currently running one. 679Kills/terminates/cancels all coros except the currently running one.
729=item $state->is_new 755=item $state->is_new
730 756
731Returns true iff this Coro object is "new", i.e. has never been run 757Returns true iff this Coro object is "new", i.e. has never been run
732yet. Those states basically consist of only the code reference to call and 758yet. Those states basically consist of only the code reference to call and
733the arguments, but consumes very little other resources. New states will 759the arguments, but consumes very little other resources. New states will
734automatically get assigned a perl interpreter when they are transfered to. 760automatically get assigned a perl interpreter when they are transferred to.
735 761
736=item $state->is_zombie 762=item $state->is_zombie
737 763
738Returns true iff the Coro object has been cancelled, i.e. 764Returns true iff the Coro object has been cancelled, i.e.
739it's resources freed because they were C<cancel>'ed, C<terminate>'d, 765its resources freed because they were C<cancel>'ed, C<terminate>'d,
740C<safe_cancel>'ed or simply went out of scope. 766C<safe_cancel>'ed or simply went out of scope.
741 767
742The name "zombie" stems from UNIX culture, where a process that has 768The name "zombie" stems from UNIX culture, where a process that has
743exited and only stores and exit status and no other resources is called a 769exited and only stores and exit status and no other resources is called a
744"zombie". 770"zombie".
757=item $is_suspended = $coro->is_suspended 783=item $is_suspended = $coro->is_suspended
758 784
759Returns true iff this Coro object has been suspended. Suspended Coros will 785Returns true iff this Coro object has been suspended. Suspended Coros will
760not ever be scheduled. 786not ever be scheduled.
761 787
762=item $coro->cancel (arg...) 788=item $coro->cancel ($arg...)
763 789
764Terminates the given Coro thread and makes it return the given arguments as 790Terminate the given Coro thread and make it return the given arguments as
765status (default: an empty list). Never returns if the Coro is the 791status (default: an empty list). Never returns if the Coro is the
766current Coro. 792current Coro.
767 793
768This is a rather brutal way to free a coro, with some limitations - if 794This is a rather brutal way to free a coro, with some limitations - if
769the thread is inside a C callback that doesn't expect to be canceled, 795the thread is inside a C callback that doesn't expect to be canceled,
770bad things can happen, or if the cancelled thread insists on running 796bad things can happen, or if the cancelled thread insists on running
771complicated cleanup handlers that rely on its thread context, things will 797complicated cleanup handlers that rely on its thread context, things will
772not work. 798not work.
773 799
774Any cleanup code being run (e.g. from C<guard> blocks) will be run without 800Any cleanup code being run (e.g. from C<guard> blocks, destructors and so
775a thread context, and is not allowed to switch to other threads. On the 801on) will be run without a thread context, and is not allowed to switch
802to other threads. A common mistake is to call C<< ->cancel >> from a
803destructor called by die'ing inside the thread to be cancelled for
804example.
805
776plus side, C<< ->cancel >> will always clean up the thread, no matter 806On the plus side, C<< ->cancel >> will always clean up the thread, no
777what. If your cleanup code is complex or you want to avoid cancelling a 807matter what. If your cleanup code is complex or you want to avoid
778C-thread that doesn't know how to clean up itself, it can be better to C<< 808cancelling a C-thread that doesn't know how to clean up itself, it can be
779->throw >> an exception, or use C<< ->safe_cancel >>. 809better to C<< ->throw >> an exception, or use C<< ->safe_cancel >>.
780 810
781The arguments to C<< ->cancel >> are not copied, but instead will 811The arguments to C<< ->cancel >> are not copied, but instead will
782be referenced directly (e.g. if you pass C<$var> and after the call 812be referenced directly (e.g. if you pass C<$var> and after the call
783change that variable, then you might change the return values passed to 813change that variable, then you might change the return values passed to
784e.g. C<join>, so don't do that). 814e.g. C<join>, so don't do that).
790 820
791=item $coro->safe_cancel ($arg...) 821=item $coro->safe_cancel ($arg...)
792 822
793Works mostly like C<< ->cancel >>, but is inherently "safer", and 823Works mostly like C<< ->cancel >>, but is inherently "safer", and
794consequently, can fail with an exception in cases the thread is not in a 824consequently, can fail with an exception in cases the thread is not in a
795cancellable state. 825cancellable state. Essentially, C<< ->safe_cancel >> is a C<< ->cancel >>
826with extra checks before canceling.
796 827
797This method works a bit like throwing an exception that cannot be caught 828It works a bit like throwing an exception that cannot be caught -
798- specifically, it will clean up the thread from within itself, so 829specifically, it will clean up the thread from within itself, so all
799all cleanup handlers (e.g. C<guard> blocks) are run with full thread 830cleanup handlers (e.g. C<guard> blocks) are run with full thread
800context and can block if they wish. The downside is that there is no 831context and can block if they wish. The downside is that there is no
801guarantee that the thread can be cancelled when you call this method, and 832guarantee that the thread can be cancelled when you call this method, and
802therefore, it might fail. It is also considerably slower than C<cancel> or 833therefore, it might fail. It is also considerably slower than C<cancel> or
803C<terminate>. 834C<terminate>.
804 835
805A thread is in a safe-cancellable state if it either hasn't been run yet, 836A thread is in a safe-cancellable state if it either has never been run
837yet, has already been canceled/terminated or otherwise destroyed, or has
806or it has no C context attached and is inside an SLF function. 838no C context attached and is inside an SLF function.
807 839
840The first two states are trivial - a thread that has not started or has
841already finished is safe to cancel.
842
808The latter two basically mean that the thread isn't currently inside a 843The last state basically means that the thread isn't currently inside a
809perl callback called from some C function (usually via some XS modules) 844perl callback called from some C function (usually via some XS modules)
810and isn't currently executing inside some C function itself (via Coro's XS 845and isn't currently executing inside some C function itself (via Coro's XS
811API). 846API).
812 847
813This call returns true when it could cancel the thread, or croaks with an 848This call returns true when it could cancel the thread, or croaks with an
885return once the C<$coro> terminates. 920return once the C<$coro> terminates.
886 921
887=item $coro->on_destroy (\&cb) 922=item $coro->on_destroy (\&cb)
888 923
889Registers a callback that is called when this coro thread gets destroyed, 924Registers a callback that is called when this coro thread gets destroyed,
890that is, after it's resources have been freed but before it is joined. The 925that is, after its resources have been freed but before it is joined. The
891callback gets passed the terminate/cancel arguments, if any, and I<must 926callback gets passed the terminate/cancel arguments, if any, and I<must
892not> die, under any circumstances. 927not> die, under any circumstances.
893 928
894There can be any number of C<on_destroy> callbacks per coro, and there is 929There can be any number of C<on_destroy> callbacks per coro, and there is
895no way currently to remove a callback once added. 930currently no way to remove a callback once added.
896 931
897=item $oldprio = $coro->prio ($newprio) 932=item $oldprio = $coro->prio ($newprio)
898 933
899Sets (or gets, if the argument is missing) the priority of the 934Sets (or gets, if the argument is missing) the priority of the
900coro thread. Higher priority coro get run before lower priority 935coro thread. Higher priority coro get run before lower priority
927coro thread. This is just a free-form string you can associate with a 962coro thread. This is just a free-form string you can associate with a
928coro. 963coro.
929 964
930This method simply sets the C<< $coro->{desc} >> member to the given 965This method simply sets the C<< $coro->{desc} >> member to the given
931string. You can modify this member directly if you wish, and in fact, this 966string. You can modify this member directly if you wish, and in fact, this
932is often preferred to indicate major processing states that cna then be 967is often preferred to indicate major processing states that can then be
933seen for example in a L<Coro::Debug> session: 968seen for example in a L<Coro::Debug> session:
934 969
935 sub my_long_function { 970 sub my_long_function {
936 local $Coro::current->{desc} = "now in my_long_function"; 971 local $Coro::current->{desc} = "now in my_long_function";
937 ... 972 ...
992otherwise you might suffer from crashes or worse. The only event library 1027otherwise you might suffer from crashes or worse. The only event library
993currently known that is safe to use without C<unblock_sub> is L<EV> (but 1028currently known that is safe to use without C<unblock_sub> is L<EV> (but
994you might still run into deadlocks if all event loops are blocked). 1029you might still run into deadlocks if all event loops are blocked).
995 1030
996Coro will try to catch you when you block in the event loop 1031Coro will try to catch you when you block in the event loop
997("FATAL:$Coro::IDLE blocked itself"), but this is just best effort and 1032("FATAL: $Coro::idle blocked itself"), but this is just best effort and
998only works when you do not run your own event loop. 1033only works when you do not run your own event loop.
999 1034
1000This function allows your callbacks to block by executing them in another 1035This function allows your callbacks to block by executing them in another
1001coro where it is safe to block. One example where blocking is handy 1036coro where it is safe to block. One example where blocking is handy
1002is when you use the L<Coro::AIO|Coro::AIO> functions to save results to 1037is when you use the L<Coro::AIO|Coro::AIO> functions to save results to
1051 1086
1052Create and return a "rouse callback". That's a code reference that, 1087Create and return a "rouse callback". That's a code reference that,
1053when called, will remember a copy of its arguments and notify the owner 1088when called, will remember a copy of its arguments and notify the owner
1054coro of the callback. 1089coro of the callback.
1055 1090
1091Only the first invocation will store agruments and signal any waiter -
1092further calls will effectively be ignored, but it is ok to try.
1093
1056See the next function. 1094Also see the next function.
1057 1095
1058=item @args = rouse_wait [$cb] 1096=item @args = rouse_wait [$cb]
1059 1097
1060Wait for the specified rouse callback (or the last one that was created in 1098Wait for the specified rouse callback to be invoked (or if the argument is
1061this coro). 1099missing, use the most recently created callback in the current coro).
1062 1100
1063As soon as the callback is invoked (or when the callback was invoked 1101As soon as the callback is invoked (or when the callback was invoked
1064before C<rouse_wait>), it will return the arguments originally passed to 1102before C<rouse_wait>), it will return the arguments originally passed to
1065the rouse callback. In scalar context, that means you get the I<last> 1103the rouse callback. In scalar context, that means you get the I<last>
1066argument, just as if C<rouse_wait> had a C<return ($a1, $a2, $a3...)> 1104argument, just as if C<rouse_wait> had a C<return ($a1, $a2, $a3...)>
1067statement at the end. 1105statement at the end.
1068 1106
1107You are only allowed to wait once for a given rouse callback.
1108
1069See the section B<HOW TO WAIT FOR A CALLBACK> for an actual usage example. 1109See the section B<HOW TO WAIT FOR A CALLBACK> for an actual usage example.
1110
1111As of Coro 6.57, you can reliably wait for a rouse callback in a different
1112thread than from where it was created.
1070 1113
1071=back 1114=back
1072 1115
1073=cut 1116=cut
1074 1117
1080 1123
1081 # some modules have their new predefined in State.xs, some don't 1124 # some modules have their new predefined in State.xs, some don't
1082 *{"Coro::$module\::new"} = $old 1125 *{"Coro::$module\::new"} = $old
1083 if $old; 1126 if $old;
1084 1127
1085 goto &{"Coro::$module\::new"}; 1128 goto &{"Coro::$module\::new"}
1086 }; 1129 };
1087} 1130}
1088 1131
10891; 11321;
1090 1133
1093It is very common for a coro to wait for some callback to be 1136It is very common for a coro to wait for some callback to be
1094called. This occurs naturally when you use coro in an otherwise 1137called. This occurs naturally when you use coro in an otherwise
1095event-based program, or when you use event-based libraries. 1138event-based program, or when you use event-based libraries.
1096 1139
1097These typically register a callback for some event, and call that callback 1140These typically register a callback for some event, and call that callback
1098when the event occured. In a coro, however, you typically want to 1141when the event occurred. In a coro, however, you typically want to
1099just wait for the event, simplyifying things. 1142just wait for the event, simplyifying things.
1100 1143
1101For example C<< AnyEvent->child >> registers a callback to be called when 1144For example C<< AnyEvent->child >> registers a callback to be called when
1102a specific child has exited: 1145a specific child has exited:
1103 1146
1106But from within a coro, you often just want to write this: 1149But from within a coro, you often just want to write this:
1107 1150
1108 my $status = wait_for_child $pid; 1151 my $status = wait_for_child $pid;
1109 1152
1110Coro offers two functions specifically designed to make this easy, 1153Coro offers two functions specifically designed to make this easy,
1111C<Coro::rouse_cb> and C<Coro::rouse_wait>. 1154C<rouse_cb> and C<rouse_wait>.
1112 1155
1113The first function, C<rouse_cb>, generates and returns a callback that, 1156The first function, C<rouse_cb>, generates and returns a callback that,
1114when invoked, will save its arguments and notify the coro that 1157when invoked, will save its arguments and notify the coro that
1115created the callback. 1158created the callback.
1116 1159
1122function mentioned above: 1165function mentioned above:
1123 1166
1124 sub wait_for_child($) { 1167 sub wait_for_child($) {
1125 my ($pid) = @_; 1168 my ($pid) = @_;
1126 1169
1127 my $watcher = AnyEvent->child (pid => $pid, cb => Coro::rouse_cb); 1170 my $watcher = AnyEvent->child (pid => $pid, cb => rouse_cb);
1128 1171
1129 my ($rpid, $rstatus) = Coro::rouse_wait; 1172 my ($rpid, $rstatus) = rouse_wait;
1130 $rstatus 1173 $rstatus
1131 } 1174 }
1132 1175
1133In the case where C<rouse_cb> and C<rouse_wait> are not flexible enough, 1176In the case where C<rouse_cb> and C<rouse_wait> are not flexible enough,
1134you can roll your own, using C<schedule>: 1177you can roll your own, using C<schedule> and C<ready>:
1135 1178
1136 sub wait_for_child($) { 1179 sub wait_for_child($) {
1137 my ($pid) = @_; 1180 my ($pid) = @_;
1138 1181
1139 # store the current coro in $current, 1182 # store the current coro in $current,
1142 my ($done, $rstatus); 1185 my ($done, $rstatus);
1143 1186
1144 # pass a closure to ->child 1187 # pass a closure to ->child
1145 my $watcher = AnyEvent->child (pid => $pid, cb => sub { 1188 my $watcher = AnyEvent->child (pid => $pid, cb => sub {
1146 $rstatus = $_[1]; # remember rstatus 1189 $rstatus = $_[1]; # remember rstatus
1147 $done = 1; # mark $rstatus as valud 1190 $done = 1; # mark $rstatus as valid
1191 $current->ready; # wake up the waiting thread
1148 }); 1192 });
1149 1193
1150 # wait until the closure has been called 1194 # wait until the closure has been called
1151 schedule while !$done; 1195 schedule while !$done;
1152 1196
1231processes. What makes it so bad is that on non-windows platforms, you can 1275processes. What makes it so bad is that on non-windows platforms, you can
1232actually take advantage of custom hardware for this purpose (as evidenced 1276actually take advantage of custom hardware for this purpose (as evidenced
1233by the forks module, which gives you the (i-) threads API, just much 1277by the forks module, which gives you the (i-) threads API, just much
1234faster). 1278faster).
1235 1279
1236Sharing data is in the i-threads model is done by transfering data 1280Sharing data is in the i-threads model is done by transferring data
1237structures between threads using copying semantics, which is very slow - 1281structures between threads using copying semantics, which is very slow -
1238shared data simply does not exist. Benchmarks using i-threads which are 1282shared data simply does not exist. Benchmarks using i-threads which are
1239communication-intensive show extremely bad behaviour with i-threads (in 1283communication-intensive show extremely bad behaviour with i-threads (in
1240fact, so bad that Coro, which cannot take direct advantage of multiple 1284fact, so bad that Coro, which cannot take direct advantage of multiple
1241CPUs, is often orders of magnitude faster because it shares data using 1285CPUs, is often orders of magnitude faster because it shares data using
1271 1315
1272XS API: L<Coro::MakeMaker>. 1316XS API: L<Coro::MakeMaker>.
1273 1317
1274Low level Configuration, Thread Environment, Continuations: L<Coro::State>. 1318Low level Configuration, Thread Environment, Continuations: L<Coro::State>.
1275 1319
1276=head1 AUTHOR 1320=head1 AUTHOR/SUPPORT/CONTACT
1277 1321
1278 Marc Lehmann <schmorp@schmorp.de> 1322 Marc A. Lehmann <schmorp@schmorp.de>
1279 http://home.schmorp.de/ 1323 http://software.schmorp.de/pkg/Coro.html
1280 1324
1281=cut 1325=cut
1282 1326

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines