… | |
… | |
72 | |
72 | |
73 | =over 4 |
73 | =over 4 |
74 | |
74 | |
75 | =item 1. Creation |
75 | =item 1. Creation |
76 | |
76 | |
77 | The first thing in the life of a coro thread is it's creation - |
77 | The first thing in the life of a coro thread is its creation - |
78 | obviously. The typical way to create a thread is to call the C<async |
78 | obviously. The typical way to create a thread is to call the C<async |
79 | BLOCK> function: |
79 | BLOCK> function: |
80 | |
80 | |
81 | async { |
81 | async { |
82 | # thread code goes here |
82 | # thread code goes here |
… | |
… | |
91 | This creates a new coro thread and puts it into the ready queue, meaning |
91 | This creates a new coro thread and puts it into the ready queue, meaning |
92 | it will run as soon as the CPU is free for it. |
92 | it will run as soon as the CPU is free for it. |
93 | |
93 | |
94 | C<async> will return a Coro object - you can store this for future |
94 | C<async> will return a Coro object - you can store this for future |
95 | reference or ignore it - a thread that is running, ready to run or waiting |
95 | reference or ignore it - a thread that is running, ready to run or waiting |
96 | for some event is alive on it's own. |
96 | for some event is alive on its own. |
97 | |
97 | |
98 | Another way to create a thread is to call the C<new> constructor with a |
98 | Another way to create a thread is to call the C<new> constructor with a |
99 | code-reference: |
99 | code-reference: |
100 | |
100 | |
101 | new Coro sub { |
101 | new Coro sub { |
… | |
… | |
248 | implements an endless loop, the C<$guard> will not be cleaned up. However, |
248 | implements an endless loop, the C<$guard> will not be cleaned up. However, |
249 | since the thread object returned by C<async> is not stored anywhere, the |
249 | since the thread object returned by C<async> is not stored anywhere, the |
250 | thread is initially referenced because it is in the ready queue, when it |
250 | thread is initially referenced because it is in the ready queue, when it |
251 | runs it is referenced by C<$Coro::current>, but when it calls C<schedule>, |
251 | runs it is referenced by C<$Coro::current>, but when it calls C<schedule>, |
252 | it gets C<cancel>ed causing the guard object to be destroyed (see the next |
252 | it gets C<cancel>ed causing the guard object to be destroyed (see the next |
253 | section), and printing it's message. |
253 | section), and printing its message. |
254 | |
254 | |
255 | If this seems a bit drastic, remember that this only happens when nothing |
255 | If this seems a bit drastic, remember that this only happens when nothing |
256 | references the thread anymore, which means there is no way to further |
256 | references the thread anymore, which means there is no way to further |
257 | execute it, ever. The only options at this point are leaking the thread, |
257 | execute it, ever. The only options at this point are leaking the thread, |
258 | or cleaning it up, which brings us to... |
258 | or cleaning it up, which brings us to... |
… | |
… | |
261 | |
261 | |
262 | Threads will allocate various resources. Most but not all will be returned |
262 | Threads will allocate various resources. Most but not all will be returned |
263 | when a thread terminates, during clean-up. |
263 | when a thread terminates, during clean-up. |
264 | |
264 | |
265 | Cleanup is quite similar to throwing an uncaught exception: perl will |
265 | Cleanup is quite similar to throwing an uncaught exception: perl will |
266 | work it's way up through all subroutine calls and blocks. On it's way, it |
266 | work its way up through all subroutine calls and blocks. On its way, it |
267 | will release all C<my> variables, undo all C<local>'s and free any other |
267 | will release all C<my> variables, undo all C<local>'s and free any other |
268 | resources truly local to the thread. |
268 | resources truly local to the thread. |
269 | |
269 | |
270 | So, a common way to free resources is to keep them referenced only by my |
270 | So, a common way to free resources is to keep them referenced only by my |
271 | variables: |
271 | variables: |
… | |
… | |
293 | code blocks): |
293 | code 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 | |
367 | our $idle; # idle handler |
367 | our $idle; # idle handler |
368 | our $main; # main coro |
368 | our $main; # main coro |
369 | our $current; # current coro |
369 | our $current; # current coro |
370 | |
370 | |
371 | our $VERSION = 6.33; |
371 | our $VERSION = 6.54; |
372 | |
372 | |
373 | our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait); |
373 | our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait); |
374 | our %EXPORT_TAGS = ( |
374 | our %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 | ); |
… | |
… | |
498 | C<async> does. As the coro is being reused, stuff like C<on_destroy> |
498 | C<async> does. As the coro is being reused, stuff like C<on_destroy> |
499 | will not work in the expected way, unless you call terminate or cancel, |
499 | will not work in the expected way, unless you call terminate or cancel, |
500 | which somehow defeats the purpose of pooling (but is fine in the |
500 | which somehow defeats the purpose of pooling (but is fine in the |
501 | exceptional case). |
501 | exceptional case). |
502 | |
502 | |
503 | The priority will be reset to C<0> after each run, tracing will be |
503 | The priority will be reset to C<0> after each run, all C<swap_sv> calls |
504 | disabled, the description will be reset and the default output filehandle |
504 | will be undone, tracing will be disabled, the description will be reset |
505 | gets restored, so you can change all these. Otherwise the coro will |
505 | and the default output filehandle gets restored, so you can change all |
506 | be re-used "as-is": most notably if you change other per-coro global |
506 | these. Otherwise the coro will be re-used "as-is": most notably if you |
507 | stuff such as C<$/> you I<must needs> revert that change, which is most |
507 | change other per-coro global stuff such as C<$/> you I<must needs> revert |
508 | simply done by using local as in: C<< local $/ >>. |
508 | that change, which is most simply done by using local as in: C<< local $/ |
|
|
509 | >>. |
509 | |
510 | |
510 | The idle pool size is limited to C<8> idle coros (this can be |
511 | The idle pool size is limited to C<8> idle coros (this can be |
511 | adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle |
512 | adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle |
512 | coros as required. |
513 | coros 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 | |
641 | This can be used to localise about any resource (locale, uid, current |
642 | This can be used to localise about any resource (locale, uid, current |
642 | working directory etc.) to a block, despite the existance of other |
643 | working directory etc.) to a block, despite the existence of other |
643 | coros. |
644 | coros. |
644 | |
645 | |
645 | Another interesting example implements time-sliced multitasking using |
646 | Another interesting example implements time-sliced multitasking using |
646 | interval timers (this could obviously be optimised, but does the job): |
647 | interval timers (this could obviously be optimised, but does the job): |
647 | |
648 | |
… | |
… | |
652 | Coro::on_enter { |
653 | Coro::on_enter { |
653 | # on entering the thread, we set an VTALRM handler to cede |
654 | # on entering the thread, we set an VTALRM handler to cede |
654 | $SIG{VTALRM} = sub { cede }; |
655 | $SIG{VTALRM} = sub { cede }; |
655 | # and then start the interval timer |
656 | # and then start the interval timer |
656 | Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0.01, 0.01; |
657 | Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0.01, 0.01; |
657 | }; |
658 | }; |
658 | Coro::on_leave { |
659 | Coro::on_leave { |
659 | # on leaving the thread, we stop the interval timer again |
660 | # on leaving the thread, we stop the interval timer again |
660 | Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0, 0; |
661 | Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0, 0; |
661 | }; |
662 | }; |
662 | |
663 | |
663 | &{+shift}; |
664 | &{+shift}; |
664 | } |
665 | } |
665 | |
666 | |
666 | # use like this: |
667 | # use like this: |
667 | timeslice { |
668 | timeslice { |
668 | # The following is an endless loop that would normally |
669 | # The following is an endless loop that would normally |
669 | # monopolise the process. Since it runs in a timesliced |
670 | # monopolise the process. Since it runs in a timesliced |
670 | # environment, it will regularly cede to other threads. |
671 | # environment, it will regularly cede to other threads. |
671 | while () { } |
672 | while () { } |
672 | }; |
673 | }; |
673 | |
674 | |
674 | |
675 | |
675 | =item killall |
676 | =item killall |
676 | |
677 | |
677 | Kills/terminates/cancels all coros except the currently running one. |
678 | Kills/terminates/cancels all coros except the currently running one. |
… | |
… | |
753 | =item $state->is_new |
754 | =item $state->is_new |
754 | |
755 | |
755 | Returns true iff this Coro object is "new", i.e. has never been run |
756 | Returns true iff this Coro object is "new", i.e. has never been run |
756 | yet. Those states basically consist of only the code reference to call and |
757 | yet. Those states basically consist of only the code reference to call and |
757 | the arguments, but consumes very little other resources. New states will |
758 | the arguments, but consumes very little other resources. New states will |
758 | automatically get assigned a perl interpreter when they are transfered to. |
759 | automatically get assigned a perl interpreter when they are transferred to. |
759 | |
760 | |
760 | =item $state->is_zombie |
761 | =item $state->is_zombie |
761 | |
762 | |
762 | Returns true iff the Coro object has been cancelled, i.e. |
763 | Returns true iff the Coro object has been cancelled, i.e. |
763 | it's resources freed because they were C<cancel>'ed, C<terminate>'d, |
764 | its resources freed because they were C<cancel>'ed, C<terminate>'d, |
764 | C<safe_cancel>'ed or simply went out of scope. |
765 | C<safe_cancel>'ed or simply went out of scope. |
765 | |
766 | |
766 | The name "zombie" stems from UNIX culture, where a process that has |
767 | The name "zombie" stems from UNIX culture, where a process that has |
767 | exited and only stores and exit status and no other resources is called a |
768 | exited 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 | |
783 | Returns true iff this Coro object has been suspended. Suspended Coros will |
784 | Returns true iff this Coro object has been suspended. Suspended Coros will |
784 | not ever be scheduled. |
785 | not ever be scheduled. |
785 | |
786 | |
786 | =item $coro->cancel (arg...) |
787 | =item $coro->cancel ($arg...) |
787 | |
788 | |
788 | Terminates the given Coro thread and makes it return the given arguments as |
789 | Terminate the given Coro thread and make it return the given arguments as |
789 | status (default: an empty list). Never returns if the Coro is the |
790 | status (default: an empty list). Never returns if the Coro is the |
790 | current Coro. |
791 | current Coro. |
791 | |
792 | |
792 | This is a rather brutal way to free a coro, with some limitations - if |
793 | This is a rather brutal way to free a coro, with some limitations - if |
793 | the thread is inside a C callback that doesn't expect to be canceled, |
794 | the thread is inside a C callback that doesn't expect to be canceled, |
794 | bad things can happen, or if the cancelled thread insists on running |
795 | bad things can happen, or if the cancelled thread insists on running |
795 | complicated cleanup handlers that rely on its thread context, things will |
796 | complicated cleanup handlers that rely on its thread context, things will |
796 | not work. |
797 | not work. |
797 | |
798 | |
798 | Any cleanup code being run (e.g. from C<guard> blocks) will be run without |
799 | Any cleanup code being run (e.g. from C<guard> blocks, destructors and so |
799 | a thread context, and is not allowed to switch to other threads. On the |
800 | on) will be run without a thread context, and is not allowed to switch |
|
|
801 | to other threads. A common mistake is to call C<< ->cancel >> from a |
|
|
802 | destructor called by die'ing inside the thread to be cancelled for |
|
|
803 | example. |
|
|
804 | |
800 | plus side, C<< ->cancel >> will always clean up the thread, no matter |
805 | On the plus side, C<< ->cancel >> will always clean up the thread, no |
801 | what. If your cleanup code is complex or you want to avoid cancelling a |
806 | matter what. If your cleanup code is complex or you want to avoid |
802 | C-thread that doesn't know how to clean up itself, it can be better to C<< |
807 | cancelling a C-thread that doesn't know how to clean up itself, it can be |
803 | ->throw >> an exception, or use C<< ->safe_cancel >>. |
808 | better to C<< ->throw >> an exception, or use C<< ->safe_cancel >>. |
804 | |
809 | |
805 | The arguments to C<< ->cancel >> are not copied, but instead will |
810 | The arguments to C<< ->cancel >> are not copied, but instead will |
806 | be referenced directly (e.g. if you pass C<$var> and after the call |
811 | be referenced directly (e.g. if you pass C<$var> and after the call |
807 | change that variable, then you might change the return values passed to |
812 | change that variable, then you might change the return values passed to |
808 | e.g. C<join>, so don't do that). |
813 | e.g. C<join>, so don't do that). |
… | |
… | |
814 | |
819 | |
815 | =item $coro->safe_cancel ($arg...) |
820 | =item $coro->safe_cancel ($arg...) |
816 | |
821 | |
817 | Works mostly like C<< ->cancel >>, but is inherently "safer", and |
822 | Works mostly like C<< ->cancel >>, but is inherently "safer", and |
818 | consequently, can fail with an exception in cases the thread is not in a |
823 | consequently, can fail with an exception in cases the thread is not in a |
819 | cancellable state. |
824 | cancellable state. Essentially, C<< ->safe_cancel >> is a C<< ->cancel >> |
|
|
825 | with extra checks before canceling. |
820 | |
826 | |
821 | This method works a bit like throwing an exception that cannot be caught |
827 | It works a bit like throwing an exception that cannot be caught - |
822 | - specifically, it will clean up the thread from within itself, so |
828 | specifically, it will clean up the thread from within itself, so all |
823 | all cleanup handlers (e.g. C<guard> blocks) are run with full thread |
829 | cleanup handlers (e.g. C<guard> blocks) are run with full thread |
824 | context and can block if they wish. The downside is that there is no |
830 | context and can block if they wish. The downside is that there is no |
825 | guarantee that the thread can be cancelled when you call this method, and |
831 | guarantee that the thread can be cancelled when you call this method, and |
826 | therefore, it might fail. It is also considerably slower than C<cancel> or |
832 | therefore, it might fail. It is also considerably slower than C<cancel> or |
827 | C<terminate>. |
833 | C<terminate>. |
828 | |
834 | |
829 | A thread is in a safe-cancellable state if it either hasn't been run yet, |
835 | A thread is in a safe-cancellable state if it either has never been run |
|
|
836 | yet, has already been canceled/terminated or otherwise destroyed, or has |
830 | or it has no C context attached and is inside an SLF function. |
837 | no C context attached and is inside an SLF function. |
831 | |
838 | |
|
|
839 | The first two states are trivial - a thread that hasnot started or has |
|
|
840 | already finished is safe to cancel. |
|
|
841 | |
832 | The latter two basically mean that the thread isn't currently inside a |
842 | The last state basically means that the thread isn't currently inside a |
833 | perl callback called from some C function (usually via some XS modules) |
843 | perl callback called from some C function (usually via some XS modules) |
834 | and isn't currently executing inside some C function itself (via Coro's XS |
844 | and isn't currently executing inside some C function itself (via Coro's XS |
835 | API). |
845 | API). |
836 | |
846 | |
837 | This call returns true when it could cancel the thread, or croaks with an |
847 | This call returns true when it could cancel the thread, or croaks with an |
… | |
… | |
909 | return once the C<$coro> terminates. |
919 | return once the C<$coro> terminates. |
910 | |
920 | |
911 | =item $coro->on_destroy (\&cb) |
921 | =item $coro->on_destroy (\&cb) |
912 | |
922 | |
913 | Registers a callback that is called when this coro thread gets destroyed, |
923 | Registers a callback that is called when this coro thread gets destroyed, |
914 | that is, after it's resources have been freed but before it is joined. The |
924 | that is, after its resources have been freed but before it is joined. The |
915 | callback gets passed the terminate/cancel arguments, if any, and I<must |
925 | callback gets passed the terminate/cancel arguments, if any, and I<must |
916 | not> die, under any circumstances. |
926 | not> die, under any circumstances. |
917 | |
927 | |
918 | There can be any number of C<on_destroy> callbacks per coro, and there is |
928 | There can be any number of C<on_destroy> callbacks per coro, and there is |
919 | currently no way to remove a callback once added. |
929 | currently no way to remove a callback once added. |
… | |
… | |
1016 | otherwise you might suffer from crashes or worse. The only event library |
1026 | otherwise you might suffer from crashes or worse. The only event library |
1017 | currently known that is safe to use without C<unblock_sub> is L<EV> (but |
1027 | currently known that is safe to use without C<unblock_sub> is L<EV> (but |
1018 | you might still run into deadlocks if all event loops are blocked). |
1028 | you might still run into deadlocks if all event loops are blocked). |
1019 | |
1029 | |
1020 | Coro will try to catch you when you block in the event loop |
1030 | Coro will try to catch you when you block in the event loop |
1021 | ("FATAL:$Coro::IDLE blocked itself"), but this is just best effort and |
1031 | ("FATAL: $Coro::idle blocked itself"), but this is just best effort and |
1022 | only works when you do not run your own event loop. |
1032 | only works when you do not run your own event loop. |
1023 | |
1033 | |
1024 | This function allows your callbacks to block by executing them in another |
1034 | This function allows your callbacks to block by executing them in another |
1025 | coro where it is safe to block. One example where blocking is handy |
1035 | coro where it is safe to block. One example where blocking is handy |
1026 | is when you use the L<Coro::AIO|Coro::AIO> functions to save results to |
1036 | is when you use the L<Coro::AIO|Coro::AIO> functions to save results to |
… | |
… | |
1117 | It is very common for a coro to wait for some callback to be |
1127 | It is very common for a coro to wait for some callback to be |
1118 | called. This occurs naturally when you use coro in an otherwise |
1128 | called. This occurs naturally when you use coro in an otherwise |
1119 | event-based program, or when you use event-based libraries. |
1129 | event-based program, or when you use event-based libraries. |
1120 | |
1130 | |
1121 | These typically register a callback for some event, and call that callback |
1131 | These typically register a callback for some event, and call that callback |
1122 | when the event occured. In a coro, however, you typically want to |
1132 | when the event occurred. In a coro, however, you typically want to |
1123 | just wait for the event, simplyifying things. |
1133 | just wait for the event, simplyifying things. |
1124 | |
1134 | |
1125 | For example C<< AnyEvent->child >> registers a callback to be called when |
1135 | For example C<< AnyEvent->child >> registers a callback to be called when |
1126 | a specific child has exited: |
1136 | a specific child has exited: |
1127 | |
1137 | |
… | |
… | |
1256 | processes. What makes it so bad is that on non-windows platforms, you can |
1266 | processes. What makes it so bad is that on non-windows platforms, you can |
1257 | actually take advantage of custom hardware for this purpose (as evidenced |
1267 | actually take advantage of custom hardware for this purpose (as evidenced |
1258 | by the forks module, which gives you the (i-) threads API, just much |
1268 | by the forks module, which gives you the (i-) threads API, just much |
1259 | faster). |
1269 | faster). |
1260 | |
1270 | |
1261 | Sharing data is in the i-threads model is done by transfering data |
1271 | Sharing data is in the i-threads model is done by transferring data |
1262 | structures between threads using copying semantics, which is very slow - |
1272 | structures between threads using copying semantics, which is very slow - |
1263 | shared data simply does not exist. Benchmarks using i-threads which are |
1273 | shared data simply does not exist. Benchmarks using i-threads which are |
1264 | communication-intensive show extremely bad behaviour with i-threads (in |
1274 | communication-intensive show extremely bad behaviour with i-threads (in |
1265 | fact, so bad that Coro, which cannot take direct advantage of multiple |
1275 | fact, so bad that Coro, which cannot take direct advantage of multiple |
1266 | CPUs, is often orders of magnitude faster because it shares data using |
1276 | CPUs, is often orders of magnitude faster because it shares data using |
… | |
… | |
1296 | |
1306 | |
1297 | XS API: L<Coro::MakeMaker>. |
1307 | XS API: L<Coro::MakeMaker>. |
1298 | |
1308 | |
1299 | Low level Configuration, Thread Environment, Continuations: L<Coro::State>. |
1309 | Low level Configuration, Thread Environment, Continuations: L<Coro::State>. |
1300 | |
1310 | |
1301 | =head1 AUTHOR |
1311 | =head1 AUTHOR/SUPPORT/CONTACT |
1302 | |
1312 | |
1303 | Marc Lehmann <schmorp@schmorp.de> |
1313 | Marc A. Lehmann <schmorp@schmorp.de> |
1304 | http://home.schmorp.de/ |
1314 | http://software.schmorp.de/pkg/Coro.html |
1305 | |
1315 | |
1306 | =cut |
1316 | =cut |
1307 | |
1317 | |