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

Comparing Coro/Coro.pm (file contents):
Revision 1.337 by root, Sun Oct 4 13:10:22 2015 UTC vs.
Revision 1.353 by root, Fri Jul 19 15:29:46 2019 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 {
248implements an endless loop, the C<$guard> will not be cleaned up. However, 248implements an endless loop, the C<$guard> will not be cleaned up. However,
249since the thread object returned by C<async> is not stored anywhere, the 249since the thread object returned by C<async> is not stored anywhere, the
250thread is initially referenced because it is in the ready queue, when it 250thread is initially referenced because it is in the ready queue, when it
251runs it is referenced by C<$Coro::current>, but when it calls C<schedule>, 251runs it is referenced by C<$Coro::current>, but when it calls C<schedule>,
252it gets C<cancel>ed causing the guard object to be destroyed (see the next 252it gets C<cancel>ed causing the guard object to be destroyed (see the next
253section), and printing it's message. 253section), and printing its message.
254 254
255If this seems a bit drastic, remember that this only happens when nothing 255If this seems a bit drastic, remember that this only happens when nothing
256references the thread anymore, which means there is no way to further 256references the thread anymore, which means there is no way to further
257execute it, ever. The only options at this point are leaking the thread, 257execute it, ever. The only options at this point are leaking the thread,
258or cleaning it up, which brings us to... 258or cleaning it up, which brings us to...
261 261
262Threads will allocate various resources. Most but not all will be returned 262Threads will allocate various resources. Most but not all will be returned
263when a thread terminates, during clean-up. 263when a thread terminates, during clean-up.
264 264
265Cleanup is quite similar to throwing an uncaught exception: perl will 265Cleanup is quite similar to throwing an uncaught exception: perl will
266work it's way up through all subroutine calls and blocks. On it's way, it 266work its way up through all subroutine calls and blocks. On its way, it
267will release all C<my> variables, undo all C<local>'s and free any other 267will release all C<my> variables, undo all C<local>'s and free any other
268resources truly local to the thread. 268resources truly local to the thread.
269 269
270So, a common way to free resources is to keep them referenced only by my 270So, a common way to free resources is to keep them referenced only by my
271variables: 271variables:
293code blocks): 293code blocks):
294 294
295 async { 295 async {
296 my $window = new Gtk2::Window "toplevel"; 296 my $window = new Gtk2::Window "toplevel";
297 # The window will not be cleaned up automatically, even when $window 297 # The window will not be cleaned up automatically, even when $window
298 # gets freed, so use a guard to ensure it's destruction 298 # gets freed, so use a guard to ensure its destruction
299 # in case of an error: 299 # in case of an error:
300 my $window_guard = Guard::guard { $window->destroy }; 300 my $window_guard = Guard::guard { $window->destroy };
301 301
302 # we are safe here 302 # we are safe here
303 }; 303 };
366 366
367our $idle; # idle handler 367our $idle; # idle handler
368our $main; # main coro 368our $main; # main coro
369our $current; # current coro 369our $current; # current coro
370 370
371our $VERSION = 6.48; 371our $VERSION = 6.55;
372 372
373our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait); 373our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait);
374our %EXPORT_TAGS = ( 374our %EXPORT_TAGS = (
375 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)], 375 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)],
376); 376);
498C<async> does. As the coro is being reused, stuff like C<on_destroy> 498C<async> does. As the coro is being reused, stuff like C<on_destroy>
499will not work in the expected way, unless you call terminate or cancel, 499will not work in the expected way, unless you call terminate or cancel,
500which somehow defeats the purpose of pooling (but is fine in the 500which somehow defeats the purpose of pooling (but is fine in the
501exceptional case). 501exceptional case).
502 502
503The priority will be reset to C<0> after each run, tracing will be 503The priority will be reset to C<0> after each run, all C<swap_sv> calls
504disabled, the description will be reset and the default output filehandle 504will be undone, tracing will be disabled, the description will be reset
505gets restored, so you can change all these. Otherwise the coro will 505and the default output filehandle gets restored, so you can change all
506be re-used "as-is": most notably if you change other per-coro global 506these. Otherwise the coro will be re-used "as-is": most notably if you
507stuff such as C<$/> you I<must needs> revert that change, which is most 507change other per-coro global stuff such as C<$/> you I<must needs> revert
508simply done by using local as in: C<< local $/ >>. 508that change, which is most simply done by using local as in: C<< local $/
509>>.
509 510
510The idle pool size is limited to C<8> idle coros (this can be 511The idle pool size is limited to C<8> idle coros (this can be
511adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle 512adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle
512coros as required. 513coros as required.
513 514
637 # at this place, the timezone is Antarctica/South_Pole, 638 # at this place, the timezone is Antarctica/South_Pole,
638 # without disturbing the TZ of any other coro. 639 # without disturbing the TZ of any other coro.
639 }; 640 };
640 641
641This can be used to localise about any resource (locale, uid, current 642This can be used to localise about any resource (locale, uid, current
642working directory etc.) to a block, despite the existance of other 643working directory etc.) to a block, despite the existence of other
643coros. 644coros.
644 645
645Another interesting example implements time-sliced multitasking using 646Another interesting example implements time-sliced multitasking using
646interval timers (this could obviously be optimised, but does the job): 647interval timers (this could obviously be optimised, but does the job):
647 648
753=item $state->is_new 754=item $state->is_new
754 755
755Returns true iff this Coro object is "new", i.e. has never been run 756Returns true iff this Coro object is "new", i.e. has never been run
756yet. Those states basically consist of only the code reference to call and 757yet. Those states basically consist of only the code reference to call and
757the arguments, but consumes very little other resources. New states will 758the arguments, but consumes very little other resources. New states will
758automatically get assigned a perl interpreter when they are transfered to. 759automatically get assigned a perl interpreter when they are transferred to.
759 760
760=item $state->is_zombie 761=item $state->is_zombie
761 762
762Returns true iff the Coro object has been cancelled, i.e. 763Returns true iff the Coro object has been cancelled, i.e.
763it's resources freed because they were C<cancel>'ed, C<terminate>'d, 764its resources freed because they were C<cancel>'ed, C<terminate>'d,
764C<safe_cancel>'ed or simply went out of scope. 765C<safe_cancel>'ed or simply went out of scope.
765 766
766The name "zombie" stems from UNIX culture, where a process that has 767The name "zombie" stems from UNIX culture, where a process that has
767exited and only stores and exit status and no other resources is called a 768exited and only stores and exit status and no other resources is called a
768"zombie". 769"zombie".
781=item $is_suspended = $coro->is_suspended 782=item $is_suspended = $coro->is_suspended
782 783
783Returns true iff this Coro object has been suspended. Suspended Coros will 784Returns true iff this Coro object has been suspended. Suspended Coros will
784not ever be scheduled. 785not ever be scheduled.
785 786
786=item $coro->cancel (arg...) 787=item $coro->cancel ($arg...)
787 788
788Terminates the given Coro thread and makes it return the given arguments as 789Terminate the given Coro thread and make it return the given arguments as
789status (default: an empty list). Never returns if the Coro is the 790status (default: an empty list). Never returns if the Coro is the
790current Coro. 791current Coro.
791 792
792This is a rather brutal way to free a coro, with some limitations - if 793This is a rather brutal way to free a coro, with some limitations - if
793the thread is inside a C callback that doesn't expect to be canceled, 794the thread is inside a C callback that doesn't expect to be canceled,
829context and can block if they wish. The downside is that there is no 830context and can block if they wish. The downside is that there is no
830guarantee that the thread can be cancelled when you call this method, and 831guarantee that the thread can be cancelled when you call this method, and
831therefore, it might fail. It is also considerably slower than C<cancel> or 832therefore, it might fail. It is also considerably slower than C<cancel> or
832C<terminate>. 833C<terminate>.
833 834
834A thread is in a safe-cancellable state if it either hasn't been run yet, 835A thread is in a safe-cancellable state if it either has never been run
836yet, has already been canceled/terminated or otherwise destroyed, or has
835or it has no C context attached and is inside an SLF function. 837no C context attached and is inside an SLF function.
836 838
839The first two states are trivial - a thread that hasnot started or has
840already finished is safe to cancel.
841
837The latter two basically mean that the thread isn't currently inside a 842The last state basically means that the thread isn't currently inside a
838perl callback called from some C function (usually via some XS modules) 843perl callback called from some C function (usually via some XS modules)
839and isn't currently executing inside some C function itself (via Coro's XS 844and isn't currently executing inside some C function itself (via Coro's XS
840API). 845API).
841 846
842This call returns true when it could cancel the thread, or croaks with an 847This call returns true when it could cancel the thread, or croaks with an
914return once the C<$coro> terminates. 919return once the C<$coro> terminates.
915 920
916=item $coro->on_destroy (\&cb) 921=item $coro->on_destroy (\&cb)
917 922
918Registers a callback that is called when this coro thread gets destroyed, 923Registers a callback that is called when this coro thread gets destroyed,
919that is, after it's resources have been freed but before it is joined. The 924that is, after its resources have been freed but before it is joined. The
920callback gets passed the terminate/cancel arguments, if any, and I<must 925callback gets passed the terminate/cancel arguments, if any, and I<must
921not> die, under any circumstances. 926not> die, under any circumstances.
922 927
923There can be any number of C<on_destroy> callbacks per coro, and there is 928There can be any number of C<on_destroy> callbacks per coro, and there is
924currently no way to remove a callback once added. 929currently no way to remove a callback once added.
1109 1114
1110 # some modules have their new predefined in State.xs, some don't 1115 # some modules have their new predefined in State.xs, some don't
1111 *{"Coro::$module\::new"} = $old 1116 *{"Coro::$module\::new"} = $old
1112 if $old; 1117 if $old;
1113 1118
1114 goto &{"Coro::$module\::new"}; 1119 goto &{"Coro::$module\::new"}
1115 }; 1120 };
1116} 1121}
1117 1122
11181; 11231;
1119 1124
1122It is very common for a coro to wait for some callback to be 1127It is very common for a coro to wait for some callback to be
1123called. This occurs naturally when you use coro in an otherwise 1128called. This occurs naturally when you use coro in an otherwise
1124event-based program, or when you use event-based libraries. 1129event-based program, or when you use event-based libraries.
1125 1130
1126These typically register a callback for some event, and call that callback 1131These typically register a callback for some event, and call that callback
1127when the event occured. In a coro, however, you typically want to 1132when the event occurred. In a coro, however, you typically want to
1128just wait for the event, simplyifying things. 1133just wait for the event, simplyifying things.
1129 1134
1130For example C<< AnyEvent->child >> registers a callback to be called when 1135For example C<< AnyEvent->child >> registers a callback to be called when
1131a specific child has exited: 1136a specific child has exited:
1132 1137
1261processes. What makes it so bad is that on non-windows platforms, you can 1266processes. What makes it so bad is that on non-windows platforms, you can
1262actually take advantage of custom hardware for this purpose (as evidenced 1267actually take advantage of custom hardware for this purpose (as evidenced
1263by the forks module, which gives you the (i-) threads API, just much 1268by the forks module, which gives you the (i-) threads API, just much
1264faster). 1269faster).
1265 1270
1266Sharing data is in the i-threads model is done by transfering data 1271Sharing data is in the i-threads model is done by transferring data
1267structures between threads using copying semantics, which is very slow - 1272structures between threads using copying semantics, which is very slow -
1268shared data simply does not exist. Benchmarks using i-threads which are 1273shared data simply does not exist. Benchmarks using i-threads which are
1269communication-intensive show extremely bad behaviour with i-threads (in 1274communication-intensive show extremely bad behaviour with i-threads (in
1270fact, so bad that Coro, which cannot take direct advantage of multiple 1275fact, so bad that Coro, which cannot take direct advantage of multiple
1271CPUs, is often orders of magnitude faster because it shares data using 1276CPUs, is often orders of magnitude faster because it shares data using

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines