… | |
… | |
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 { |
… | |
… | |
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 | |
193 | Another way to terminate is to call C<< Coro::terminate >>, which at any |
193 | Another way to terminate is to call C<< Coro::terminate >>, the |
194 | subroutine call nesting level: |
194 | thread-equivalent of C<exit>, which works at any subroutine call nesting |
|
|
195 | level: |
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 | |
200 | And yet another way is to C<< ->cancel >> (or C<< ->safe_cancel >>) the |
201 | Yet another way is to C<< ->cancel >> (or C<< ->safe_cancel >>) the coro |
201 | coro thread from another thread: |
202 | thread from another thread: |
202 | |
203 | |
203 | my $coro = async { |
204 | my $coro = async { |
204 | exit 1; |
205 | exit 1; |
205 | }; |
206 | }; |
206 | |
207 | |
… | |
… | |
218 | So, cancelling a thread that runs in an XS event loop might not be the |
219 | So, cancelling a thread that runs in an XS event loop might not be the |
219 | best idea, but any other combination that deals with perl only (cancelling |
220 | best idea, but any other combination that deals with perl only (cancelling |
220 | when a thread is in a C<tie> method or an C<AUTOLOAD> for example) is |
221 | when a thread is in a C<tie> method or an C<AUTOLOAD> for example) is |
221 | safe. |
222 | safe. |
222 | |
223 | |
223 | Lastly, a coro thread object that isn't referenced is C<< ->cancel >>'ed |
224 | Last not least, a coro thread object that isn't referenced is C<< |
224 | automatically - just like other objects in Perl. This is not such a common |
225 | ->cancel >>'ed automatically - just like other objects in Perl. This |
225 | case, however - a running thread is referencedy b C<$Coro::current>, a |
226 | is not such a common case, however - a running thread is referencedy by |
226 | thread ready to run is referenced by the ready queue, a thread waiting |
227 | C<$Coro::current>, a thread ready to run is referenced by the ready queue, |
227 | on a lock or semaphore is referenced by being in some wait list and so |
228 | a thread waiting on a lock or semaphore is referenced by being in some |
228 | on. But a thread that isn't in any of those queues gets cancelled: |
229 | wait list and so on. But a thread that isn't in any of those queues gets |
|
|
230 | cancelled: |
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 | |
|
|
239 | A 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 | |
|
|
248 | Superficially one might not expect any output - since the C<async> |
|
|
249 | implements an endless loop, the C<$guard> will not be cleaned up. However, |
|
|
250 | since the thread object returned by C<async> is not stored anywhere, the |
|
|
251 | thread is initially referenced because it is in the ready queue, when it |
|
|
252 | runs it is referenced by C<$Coro::current>, but when it calls C<schedule>, |
|
|
253 | it gets C<cancel>ed causing the guard object to be destroyed (see the next |
|
|
254 | section), and printing its message. |
|
|
255 | |
|
|
256 | If this seems a bit drastic, remember that this only happens when nothing |
|
|
257 | references the thread anymore, which means there is no way to further |
|
|
258 | execute it, ever. The only options at this point are leaking the thread, |
|
|
259 | or cleaning it up, which brings us to... |
|
|
260 | |
237 | =item 5. Cleanup |
261 | =item 5. Cleanup |
238 | |
262 | |
239 | Threads will allocate various resources. Most but not all will be returned |
263 | Threads will allocate various resources. Most but not all will be returned |
240 | when a thread terminates, during clean-up. |
264 | when a thread terminates, during clean-up. |
241 | |
265 | |
242 | Cleanup is quite similar to throwing an uncaught exception: perl will |
266 | Cleanup is quite similar to throwing an uncaught exception: perl will |
243 | work it's way up through all subroutine calls and blocks. On it's way, it |
267 | work its way up through all subroutine calls and blocks. On its way, it |
244 | will release all C<my> variables, undo all C<local>'s and free any other |
268 | will release all C<my> variables, undo all C<local>'s and free any other |
245 | resources truly local to the thread. |
269 | resources truly local to the thread. |
246 | |
270 | |
247 | So, a common way to free resources is to keep them referenced only by my |
271 | So, a common way to free resources is to keep them referenced only by my |
248 | variables: |
272 | variables: |
… | |
… | |
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 | |
268 | The C<Guard::guard> function comes in handy for any custom cleanup you |
292 | The C<Guard::guard> function comes in handy for any custom cleanup you |
269 | might want to do (but you cannot switch to other coroutines form those |
293 | might want to do (but you cannot switch to other coroutines from those |
270 | code blocks): |
294 | code 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 | |
293 | Even after a thread has terminated and cleaned up its resources, the Coro |
317 | Even after a thread has terminated and cleaned up its resources, the Coro |
294 | object still is there and stores the return values of the thread. |
318 | object still is there and stores the return values of the thread. |
295 | |
319 | |
296 | The means the Coro object gets freed automatically when the thread has |
320 | When there are no other references, it will simply be cleaned up and |
297 | terminated and cleaned up and there arenot other references. |
321 | freed. |
298 | |
322 | |
299 | If there are, the Coro object will stay around, and you can call C<< |
323 | If there areany references, the Coro object will stay around, and you |
300 | ->join >> as many times as you wish to retrieve the result values: |
324 | can call C<< ->join >> as many times as you wish to retrieve the result |
|
|
325 | values: |
301 | |
326 | |
302 | async { |
327 | async { |
303 | print "hi\n"; |
328 | print "hi\n"; |
304 | 1 |
329 | 1 |
305 | }; |
330 | }; |
… | |
… | |
342 | |
367 | |
343 | our $idle; # idle handler |
368 | our $idle; # idle handler |
344 | our $main; # main coro |
369 | our $main; # main coro |
345 | our $current; # current coro |
370 | our $current; # current coro |
346 | |
371 | |
347 | our $VERSION = 6.05; |
372 | our $VERSION = 6.57; |
348 | |
373 | |
349 | our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait); |
374 | our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait); |
350 | our %EXPORT_TAGS = ( |
375 | our %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 | |
361 | This variable stores the Coro object that represents the main |
386 | This variable stores the Coro object that represents the main |
362 | program. While you cna C<ready> it and do most other things you can do to |
387 | program. While you can C<ready> it and do most other things you can do to |
363 | coro, it is mainly useful to compare again C<$Coro::current>, to see |
388 | coro, it is mainly useful to compare again C<$Coro::current>, to see |
364 | whether you are running in the main program or not. |
389 | whether you are running in the main program or not. |
365 | |
390 | |
366 | =cut |
391 | =cut |
367 | |
392 | |
… | |
… | |
474 | C<async> does. As the coro is being reused, stuff like C<on_destroy> |
499 | C<async> does. As the coro is being reused, stuff like C<on_destroy> |
475 | will not work in the expected way, unless you call terminate or cancel, |
500 | will not work in the expected way, unless you call terminate or cancel, |
476 | which somehow defeats the purpose of pooling (but is fine in the |
501 | which somehow defeats the purpose of pooling (but is fine in the |
477 | exceptional case). |
502 | exceptional case). |
478 | |
503 | |
479 | The priority will be reset to C<0> after each run, tracing will be |
504 | The priority will be reset to C<0> after each run, all C<swap_sv> calls |
480 | disabled, the description will be reset and the default output filehandle |
505 | will be undone, tracing will be disabled, the description will be reset |
481 | gets restored, so you can change all these. Otherwise the coro will |
506 | and the default output filehandle gets restored, so you can change all |
482 | be re-used "as-is": most notably if you change other per-coro global |
507 | these. Otherwise the coro will be re-used "as-is": most notably if you |
483 | stuff such as C<$/> you I<must needs> revert that change, which is most |
508 | change other per-coro global stuff such as C<$/> you I<must needs> revert |
484 | simply done by using local as in: C<< local $/ >>. |
509 | that change, which is most simply done by using local as in: C<< local $/ |
|
|
510 | >>. |
485 | |
511 | |
486 | The idle pool size is limited to C<8> idle coros (this can be |
512 | The idle pool size is limited to C<8> idle coros (this can be |
487 | adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle |
513 | adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle |
488 | coros as required. |
514 | coros 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 | |
617 | This can be used to localise about any resource (locale, uid, current |
643 | This can be used to localise about any resource (locale, uid, current |
618 | working directory etc.) to a block, despite the existance of other |
644 | working directory etc.) to a block, despite the existence of other |
619 | coros. |
645 | coros. |
620 | |
646 | |
621 | Another interesting example implements time-sliced multitasking using |
647 | Another interesting example implements time-sliced multitasking using |
622 | interval timers (this could obviously be optimised, but does the job): |
648 | interval 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 | |
653 | Kills/terminates/cancels all coros except the currently running one. |
679 | Kills/terminates/cancels all coros except the currently running one. |
… | |
… | |
729 | =item $state->is_new |
755 | =item $state->is_new |
730 | |
756 | |
731 | Returns true iff this Coro object is "new", i.e. has never been run |
757 | Returns true iff this Coro object is "new", i.e. has never been run |
732 | yet. Those states basically consist of only the code reference to call and |
758 | yet. Those states basically consist of only the code reference to call and |
733 | the arguments, but consumes very little other resources. New states will |
759 | the arguments, but consumes very little other resources. New states will |
734 | automatically get assigned a perl interpreter when they are transfered to. |
760 | automatically get assigned a perl interpreter when they are transferred to. |
735 | |
761 | |
736 | =item $state->is_zombie |
762 | =item $state->is_zombie |
737 | |
763 | |
738 | Returns true iff the Coro object has been cancelled, i.e. |
764 | Returns true iff the Coro object has been cancelled, i.e. |
739 | it's resources freed because they were C<cancel>'ed, C<terminate>'d, |
765 | its resources freed because they were C<cancel>'ed, C<terminate>'d, |
740 | C<safe_cancel>'ed or simply went out of scope. |
766 | C<safe_cancel>'ed or simply went out of scope. |
741 | |
767 | |
742 | The name "zombie" stems from UNIX culture, where a process that has |
768 | The name "zombie" stems from UNIX culture, where a process that has |
743 | exited and only stores and exit status and no other resources is called a |
769 | exited 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 | |
759 | Returns true iff this Coro object has been suspended. Suspended Coros will |
785 | Returns true iff this Coro object has been suspended. Suspended Coros will |
760 | not ever be scheduled. |
786 | not ever be scheduled. |
761 | |
787 | |
762 | =item $coro->cancel (arg...) |
788 | =item $coro->cancel ($arg...) |
763 | |
789 | |
764 | Terminates the given Coro thread and makes it return the given arguments as |
790 | Terminate the given Coro thread and make it return the given arguments as |
765 | status (default: an empty list). Never returns if the Coro is the |
791 | status (default: an empty list). Never returns if the Coro is the |
766 | current Coro. |
792 | current Coro. |
767 | |
793 | |
768 | This is a rather brutal way to free a coro, with some limitations - if |
794 | This is a rather brutal way to free a coro, with some limitations - if |
769 | the thread is inside a C callback that doesn't expect to be canceled, |
795 | the thread is inside a C callback that doesn't expect to be canceled, |
770 | bad things can happen, or if the cancelled thread insists on running |
796 | bad things can happen, or if the cancelled thread insists on running |
771 | complicated cleanup handlers that rely on its thread context, things will |
797 | complicated cleanup handlers that rely on its thread context, things will |
772 | not work. |
798 | not work. |
773 | |
799 | |
774 | Any cleanup code being run (e.g. from C<guard> blocks) will be run without |
800 | Any cleanup code being run (e.g. from C<guard> blocks, destructors and so |
775 | a thread context, and is not allowed to switch to other threads. On the |
801 | on) will be run without a thread context, and is not allowed to switch |
|
|
802 | to other threads. A common mistake is to call C<< ->cancel >> from a |
|
|
803 | destructor called by die'ing inside the thread to be cancelled for |
|
|
804 | example. |
|
|
805 | |
776 | plus side, C<< ->cancel >> will always clean up the thread, no matter |
806 | On the plus side, C<< ->cancel >> will always clean up the thread, no |
777 | what. If your cleanup code is complex or you want to avoid cancelling a |
807 | matter what. If your cleanup code is complex or you want to avoid |
778 | C-thread that doesn't know how to clean up itself, it can be better to C<< |
808 | cancelling a C-thread that doesn't know how to clean up itself, it can be |
779 | ->throw >> an exception, or use C<< ->safe_cancel >>. |
809 | better to C<< ->throw >> an exception, or use C<< ->safe_cancel >>. |
780 | |
810 | |
781 | The arguments to C<< ->cancel >> are not copied, but instead will |
811 | The arguments to C<< ->cancel >> are not copied, but instead will |
782 | be referenced directly (e.g. if you pass C<$var> and after the call |
812 | be referenced directly (e.g. if you pass C<$var> and after the call |
783 | change that variable, then you might change the return values passed to |
813 | change that variable, then you might change the return values passed to |
784 | e.g. C<join>, so don't do that). |
814 | e.g. C<join>, so don't do that). |
… | |
… | |
790 | |
820 | |
791 | =item $coro->safe_cancel ($arg...) |
821 | =item $coro->safe_cancel ($arg...) |
792 | |
822 | |
793 | Works mostly like C<< ->cancel >>, but is inherently "safer", and |
823 | Works mostly like C<< ->cancel >>, but is inherently "safer", and |
794 | consequently, can fail with an exception in cases the thread is not in a |
824 | consequently, can fail with an exception in cases the thread is not in a |
795 | cancellable state. |
825 | cancellable state. Essentially, C<< ->safe_cancel >> is a C<< ->cancel >> |
|
|
826 | with extra checks before canceling. |
796 | |
827 | |
797 | This method works a bit like throwing an exception that cannot be caught |
828 | It works a bit like throwing an exception that cannot be caught - |
798 | - specifically, it will clean up the thread from within itself, so |
829 | specifically, it will clean up the thread from within itself, so all |
799 | all cleanup handlers (e.g. C<guard> blocks) are run with full thread |
830 | cleanup handlers (e.g. C<guard> blocks) are run with full thread |
800 | context and can block if they wish. The downside is that there is no |
831 | context and can block if they wish. The downside is that there is no |
801 | guarantee that the thread can be cancelled when you call this method, and |
832 | guarantee that the thread can be cancelled when you call this method, and |
802 | therefore, it might fail. It is also considerably slower than C<cancel> or |
833 | therefore, it might fail. It is also considerably slower than C<cancel> or |
803 | C<terminate>. |
834 | C<terminate>. |
804 | |
835 | |
805 | A thread is in a safe-cancellable state if it either hasn't been run yet, |
836 | A thread is in a safe-cancellable state if it either has never been run |
|
|
837 | yet, has already been canceled/terminated or otherwise destroyed, or has |
806 | or it has no C context attached and is inside an SLF function. |
838 | no C context attached and is inside an SLF function. |
807 | |
839 | |
|
|
840 | The first two states are trivial - a thread that has not started or has |
|
|
841 | already finished is safe to cancel. |
|
|
842 | |
808 | The latter two basically mean that the thread isn't currently inside a |
843 | The last state basically means that the thread isn't currently inside a |
809 | perl callback called from some C function (usually via some XS modules) |
844 | perl callback called from some C function (usually via some XS modules) |
810 | and isn't currently executing inside some C function itself (via Coro's XS |
845 | and isn't currently executing inside some C function itself (via Coro's XS |
811 | API). |
846 | API). |
812 | |
847 | |
813 | This call returns true when it could cancel the thread, or croaks with an |
848 | This call returns true when it could cancel the thread, or croaks with an |
… | |
… | |
885 | return once the C<$coro> terminates. |
920 | return once the C<$coro> terminates. |
886 | |
921 | |
887 | =item $coro->on_destroy (\&cb) |
922 | =item $coro->on_destroy (\&cb) |
888 | |
923 | |
889 | Registers a callback that is called when this coro thread gets destroyed, |
924 | Registers a callback that is called when this coro thread gets destroyed, |
890 | that is, after it's resources have been freed but before it is joined. The |
925 | that is, after its resources have been freed but before it is joined. The |
891 | callback gets passed the terminate/cancel arguments, if any, and I<must |
926 | callback gets passed the terminate/cancel arguments, if any, and I<must |
892 | not> die, under any circumstances. |
927 | not> die, under any circumstances. |
893 | |
928 | |
894 | There can be any number of C<on_destroy> callbacks per coro, and there is |
929 | There can be any number of C<on_destroy> callbacks per coro, and there is |
895 | no way currently to remove a callback once added. |
930 | currently no way to remove a callback once added. |
896 | |
931 | |
897 | =item $oldprio = $coro->prio ($newprio) |
932 | =item $oldprio = $coro->prio ($newprio) |
898 | |
933 | |
899 | Sets (or gets, if the argument is missing) the priority of the |
934 | Sets (or gets, if the argument is missing) the priority of the |
900 | coro thread. Higher priority coro get run before lower priority |
935 | coro thread. Higher priority coro get run before lower priority |
… | |
… | |
927 | coro thread. This is just a free-form string you can associate with a |
962 | coro thread. This is just a free-form string you can associate with a |
928 | coro. |
963 | coro. |
929 | |
964 | |
930 | This method simply sets the C<< $coro->{desc} >> member to the given |
965 | This method simply sets the C<< $coro->{desc} >> member to the given |
931 | string. You can modify this member directly if you wish, and in fact, this |
966 | string. You can modify this member directly if you wish, and in fact, this |
932 | is often preferred to indicate major processing states that cna then be |
967 | is often preferred to indicate major processing states that can then be |
933 | seen for example in a L<Coro::Debug> session: |
968 | seen 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 | ... |
… | |
… | |
992 | otherwise you might suffer from crashes or worse. The only event library |
1027 | otherwise you might suffer from crashes or worse. The only event library |
993 | currently known that is safe to use without C<unblock_sub> is L<EV> (but |
1028 | currently known that is safe to use without C<unblock_sub> is L<EV> (but |
994 | you might still run into deadlocks if all event loops are blocked). |
1029 | you might still run into deadlocks if all event loops are blocked). |
995 | |
1030 | |
996 | Coro will try to catch you when you block in the event loop |
1031 | Coro 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 |
998 | only works when you do not run your own event loop. |
1033 | only works when you do not run your own event loop. |
999 | |
1034 | |
1000 | This function allows your callbacks to block by executing them in another |
1035 | This function allows your callbacks to block by executing them in another |
1001 | coro where it is safe to block. One example where blocking is handy |
1036 | coro where it is safe to block. One example where blocking is handy |
1002 | is when you use the L<Coro::AIO|Coro::AIO> functions to save results to |
1037 | is when you use the L<Coro::AIO|Coro::AIO> functions to save results to |
… | |
… | |
1051 | |
1086 | |
1052 | Create and return a "rouse callback". That's a code reference that, |
1087 | Create and return a "rouse callback". That's a code reference that, |
1053 | when called, will remember a copy of its arguments and notify the owner |
1088 | when called, will remember a copy of its arguments and notify the owner |
1054 | coro of the callback. |
1089 | coro of the callback. |
1055 | |
1090 | |
|
|
1091 | Only the first invocation will store agruments and signal any waiter - |
|
|
1092 | further calls will effectively be ignored, but it is ok to try. |
|
|
1093 | |
1056 | See the next function. |
1094 | Also see the next function. |
1057 | |
1095 | |
1058 | =item @args = rouse_wait [$cb] |
1096 | =item @args = rouse_wait [$cb] |
1059 | |
1097 | |
1060 | Wait for the specified rouse callback (or the last one that was created in |
1098 | Wait for the specified rouse callback to be invoked (or if the argument is |
1061 | this coro). |
1099 | missing, use the most recently created callback in the current coro). |
1062 | |
1100 | |
1063 | As soon as the callback is invoked (or when the callback was invoked |
1101 | As soon as the callback is invoked (or when the callback was invoked |
1064 | before C<rouse_wait>), it will return the arguments originally passed to |
1102 | before C<rouse_wait>), it will return the arguments originally passed to |
1065 | the rouse callback. In scalar context, that means you get the I<last> |
1103 | the rouse callback. In scalar context, that means you get the I<last> |
1066 | argument, just as if C<rouse_wait> had a C<return ($a1, $a2, $a3...)> |
1104 | argument, just as if C<rouse_wait> had a C<return ($a1, $a2, $a3...)> |
1067 | statement at the end. |
1105 | statement at the end. |
1068 | |
1106 | |
|
|
1107 | You are only allowed to wait once for a given rouse callback. |
|
|
1108 | |
1069 | See the section B<HOW TO WAIT FOR A CALLBACK> for an actual usage example. |
1109 | See the section B<HOW TO WAIT FOR A CALLBACK> for an actual usage example. |
|
|
1110 | |
|
|
1111 | As of Coro 6.57, you can reliably wait for a rouse callback in a different |
|
|
1112 | thread 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 | |
1089 | 1; |
1132 | 1; |
1090 | |
1133 | |
… | |
… | |
1093 | It is very common for a coro to wait for some callback to be |
1136 | It is very common for a coro to wait for some callback to be |
1094 | called. This occurs naturally when you use coro in an otherwise |
1137 | called. This occurs naturally when you use coro in an otherwise |
1095 | event-based program, or when you use event-based libraries. |
1138 | event-based program, or when you use event-based libraries. |
1096 | |
1139 | |
1097 | These typically register a callback for some event, and call that callback |
1140 | These typically register a callback for some event, and call that callback |
1098 | when the event occured. In a coro, however, you typically want to |
1141 | when the event occurred. In a coro, however, you typically want to |
1099 | just wait for the event, simplyifying things. |
1142 | just wait for the event, simplyifying things. |
1100 | |
1143 | |
1101 | For example C<< AnyEvent->child >> registers a callback to be called when |
1144 | For example C<< AnyEvent->child >> registers a callback to be called when |
1102 | a specific child has exited: |
1145 | a specific child has exited: |
1103 | |
1146 | |
… | |
… | |
1106 | But from within a coro, you often just want to write this: |
1149 | But 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 | |
1110 | Coro offers two functions specifically designed to make this easy, |
1153 | Coro offers two functions specifically designed to make this easy, |
1111 | C<Coro::rouse_cb> and C<Coro::rouse_wait>. |
1154 | C<rouse_cb> and C<rouse_wait>. |
1112 | |
1155 | |
1113 | The first function, C<rouse_cb>, generates and returns a callback that, |
1156 | The first function, C<rouse_cb>, generates and returns a callback that, |
1114 | when invoked, will save its arguments and notify the coro that |
1157 | when invoked, will save its arguments and notify the coro that |
1115 | created the callback. |
1158 | created the callback. |
1116 | |
1159 | |
… | |
… | |
1122 | function mentioned above: |
1165 | function 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 | |
1133 | In the case where C<rouse_cb> and C<rouse_wait> are not flexible enough, |
1176 | In the case where C<rouse_cb> and C<rouse_wait> are not flexible enough, |
1134 | you can roll your own, using C<schedule>: |
1177 | you 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 | |
… | |
… | |
1231 | processes. What makes it so bad is that on non-windows platforms, you can |
1275 | processes. What makes it so bad is that on non-windows platforms, you can |
1232 | actually take advantage of custom hardware for this purpose (as evidenced |
1276 | actually take advantage of custom hardware for this purpose (as evidenced |
1233 | by the forks module, which gives you the (i-) threads API, just much |
1277 | by the forks module, which gives you the (i-) threads API, just much |
1234 | faster). |
1278 | faster). |
1235 | |
1279 | |
1236 | Sharing data is in the i-threads model is done by transfering data |
1280 | Sharing data is in the i-threads model is done by transferring data |
1237 | structures between threads using copying semantics, which is very slow - |
1281 | structures between threads using copying semantics, which is very slow - |
1238 | shared data simply does not exist. Benchmarks using i-threads which are |
1282 | shared data simply does not exist. Benchmarks using i-threads which are |
1239 | communication-intensive show extremely bad behaviour with i-threads (in |
1283 | communication-intensive show extremely bad behaviour with i-threads (in |
1240 | fact, so bad that Coro, which cannot take direct advantage of multiple |
1284 | fact, so bad that Coro, which cannot take direct advantage of multiple |
1241 | CPUs, is often orders of magnitude faster because it shares data using |
1285 | CPUs, is often orders of magnitude faster because it shares data using |
… | |
… | |
1271 | |
1315 | |
1272 | XS API: L<Coro::MakeMaker>. |
1316 | XS API: L<Coro::MakeMaker>. |
1273 | |
1317 | |
1274 | Low level Configuration, Thread Environment, Continuations: L<Coro::State>. |
1318 | Low 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 | |