… | |
… | |
24 | Threads but don't run in parallel. |
24 | Threads but don't run in parallel. |
25 | |
25 | |
26 | This module is still experimental, see the BUGS section below. |
26 | This module is still experimental, see the BUGS section below. |
27 | |
27 | |
28 | In this module, coroutines are defined as "callchain + lexical variables |
28 | In this module, coroutines are defined as "callchain + lexical variables |
29 | + @_ + $_ + $@ + $^W), that is, a coroutine has it's own callchain, it's |
29 | + @_ + $_ + $@ + $^W + C stack), that is, a coroutine has it's own |
30 | own set of lexicals and it's own set of perl's most important global |
30 | callchain, it's own set of lexicals and it's own set of perl's most |
31 | variables. |
31 | important global variables. |
32 | |
|
|
33 | WARNING: When using this module, make sure that, at program end, no |
|
|
34 | coroutines are still running OR just call exit before falling off the |
|
|
35 | end. The reason for this is that some coroutine of yours might have called |
|
|
36 | into a C function, and falling off the end of main:: results in returning |
|
|
37 | to that C function instead if to the main C interpreter. |
|
|
38 | |
|
|
39 | WARNING: Unless you really know what you are doing, do NOT do context |
|
|
40 | switches inside callbacks from the XS level. The reason for this is |
|
|
41 | similar to the reason above: A callback calls a perl function, this |
|
|
42 | perl function does a context switch, some other callback is called, the |
|
|
43 | original function returns from it - to what? To the wrong XS function, |
|
|
44 | with totally different return values. Unfortunately, this includes |
|
|
45 | callbacks done by perl itself (tie'd variables!). |
|
|
46 | |
|
|
47 | The only workaround for this is to do coroutines on C level. |
|
|
48 | |
32 | |
49 | =cut |
33 | =cut |
50 | |
34 | |
51 | package Coro; |
35 | package Coro; |
52 | |
36 | |
… | |
… | |
189 | |
173 | |
190 | Future versions of this function will allow result arguments. |
174 | Future versions of this function will allow result arguments. |
191 | |
175 | |
192 | =cut |
176 | =cut |
193 | |
177 | |
|
|
178 | # this coroutine is necessary because a coroutine |
|
|
179 | # cannot destroy itself. |
|
|
180 | my @destroy; |
|
|
181 | my $terminate = new Coro sub { |
|
|
182 | while() { |
|
|
183 | delete ((pop @destroy)->{_coro_state}) while @destroy; |
|
|
184 | &schedule; |
|
|
185 | } |
|
|
186 | }; |
|
|
187 | |
194 | sub terminate { |
188 | sub terminate { |
195 | my $self = $current; |
189 | push @destroy, $current; |
196 | $self->{_results} = [@_]; |
190 | $terminate->ready; |
197 | $current = shift @ready || $idle; |
191 | &schedule; |
198 | Coro::State::transfer(delete $self->{_coro_state}, $current); |
192 | # NORETURN |
199 | # cannot return |
|
|
200 | die; |
|
|
201 | } |
193 | } |
202 | |
194 | |
203 | =back |
195 | =back |
204 | |
196 | |
205 | # dynamic methods |
197 | # dynamic methods |