ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/State.pm
Revision: 1.108
Committed: Wed Sep 24 07:30:12 2008 UTC (15 years, 8 months ago) by root
Branch: MAIN
Changes since 1.107: +1 -1 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3     Coro::State - create and manage simple coroutines
4    
5     =head1 SYNOPSIS
6    
7     use Coro::State;
8    
9     $new = new Coro::State sub {
10 root 1.3 print "in coroutine (called with @_), switching back\n";
11 root 1.43 $new->transfer ($main);
12 root 1.1 print "in coroutine again, switching back\n";
13 root 1.43 $new->transfer ($main);
14 root 1.3 }, 5;
15 root 1.1
16     $main = new Coro::State;
17    
18     print "in main, switching to coroutine\n";
19 root 1.43 $main->transfer ($new);
20 root 1.1 print "back in main, switch to coroutine again\n";
21 root 1.43 $main->transfer ($new);
22 root 1.1 print "back in main\n";
23    
24     =head1 DESCRIPTION
25    
26     This module implements coroutines. Coroutines, similar to continuations,
27     allow you to run more than one "thread of execution" in parallel. Unlike
28 root 1.42 threads, there is no parallelism and only voluntary switching is used so
29     locking problems are greatly reduced.
30    
31     This can be used to implement non-local jumps, exception handling,
32 root 1.94 (non-clonable) continuations and more.
33 root 1.1
34     This module provides only low-level functionality. See L<Coro> and related
35 root 1.42 modules for a higher level process abstraction including scheduling.
36 root 1.1
37 root 1.86 =head2 MODEL
38    
39     Coro::State implements two different coroutine models: Perl and C. The
40     C coroutines (called cctx's) are basically simplified perl interpreters
41     running/interpreting the Perl coroutines. A single interpreter can run any
42     number of Perl coroutines, so usually there are very few C coroutines.
43    
44     When Perl code calls a C function (e.g. in an extension module) and that
45     C function then calls back into Perl or does a coroutine switch the C
46     coroutine can no longer execute other Perl coroutines, so it stays tied to
47     the specific coroutine until it returns to the original Perl caller, after
48     which it is again avaikable to run other Perl coroutines.
49    
50     The main program always has its own "C coroutine" (which really is
51     *the* Perl interpreter running the whole program), so there will always
52 root 1.94 be at least one additional C coroutine. You can use the debugger (see
53 root 1.86 L<Coro::Debug>) to find out which coroutines are tied to their cctx and
54     which aren't.
55    
56 root 1.9 =head2 MEMORY CONSUMPTION
57    
58     A newly created coroutine that has not been used only allocates a
59 root 1.84 relatively small (a hundred bytes) structure. Only on the first
60 root 1.94 C<transfer> will perl allocate stacks (a few kb, 64 bit architetcures
61     use twice as much, i.e. a few kb :) and optionally a C stack/coroutine
62     (cctx) for coroutines that recurse through C functions. All this is very
63     system-dependent. On my x86-pc-linux-gnu system this amounts to about 2k
64     per (non-trivial but simple) coroutine.
65    
66     You can view the actual memory consumption using Coro::Debug. Keep in mind
67     that a for loop or other block constructs can easily consume 100-200 bytes
68     per nesting level.
69 root 1.1
70     =cut
71    
72     package Coro::State;
73    
74 root 1.47 use strict;
75     no warnings "uninitialized";
76    
77 root 1.84 use Carp;
78 root 1.87
79     our $DIEHOOK;
80     our $WARNHOOK;
81    
82     BEGIN {
83     $DIEHOOK = sub { };
84     $WARNHOOK = sub { warn $_[0] };
85     }
86    
87     sub diehook { &$DIEHOOK }
88     sub warnhook { &$WARNHOOK }
89 root 1.84
90 root 1.47 use XSLoader;
91 root 1.18
92 root 1.1 BEGIN {
93 root 1.108 our $VERSION = 4.748;
94 root 1.1
95 root 1.67 # must be done here because the xs part expects it to exist
96     # it might exist already because Coro::Specific created it.
97     $Coro::current ||= { };
98    
99 root 1.101 {
100     # save/restore the handlers before/after overwriting %SIG magic
101     local $SIG{__DIE__};
102     local $SIG{__WARN__};
103    
104     XSLoader::load __PACKAGE__, $VERSION;
105     }
106    
107     # need to do it after overwriting the %SIG magic
108     $SIG{__DIE__} ||= \&diehook;
109     $SIG{__WARN__} ||= \&warnhook;
110 root 1.1 }
111    
112 root 1.51 use Exporter;
113 root 1.47 use base Exporter::;
114 root 1.5
115 root 1.84 =head2 GLOBAL VARIABLES
116    
117     =over 4
118    
119     =item $Coro::State::DIEHOOK
120    
121     This works similarly to C<$SIG{__DIE__}> and is used as the default die
122     hook for newly created coroutines. This is useful if you want some generic
123     logging function that works for all coroutines that don't set their own
124     hook.
125    
126     When Coro::State is first loaded it will install these handlers for the
127 root 1.101 main program, too, unless they have been overwritten already.
128 root 1.84
129 root 1.100 The default handlers provided will behave like the built-in ones (as if
130 root 1.84 they weren't there).
131    
132 root 1.94 Note 1: You I<must> store a valid code reference in these variables,
133     C<undef> will I<not> do.
134 root 1.84
135 root 1.89 Note 2: The value of this variable will be shared among all coroutines, so
136 root 1.100 changing its value will change it in all coroutines that don't have their
137     own die handler.
138 root 1.84
139     =item $Coro::State::WARNHOOK
140    
141     Similar to above die hook, but augments C<$SIG{__WARN__}>.
142    
143     =back
144    
145     =head2 FUNCTIONS
146    
147     =over 4
148    
149 root 1.65 =item $coro = new Coro::State [$coderef[, @args...]]
150 root 1.1
151     Create a new coroutine and return it. The first C<transfer> call to this
152 root 1.94 coroutine will start execution at the given coderef.
153    
154     If the subroutine returns the program will be terminated as if execution
155     of the main program ended.
156    
157     If it throws an exception the program will terminate unless the exception
158     is caught, exactly like in the main program.
159 root 1.74
160     Calling C<exit> in a coroutine does the same as calling it in the main
161     program.
162 root 1.1
163     If the coderef is omitted this function will create a new "empty"
164     coroutine, i.e. a coroutine that cannot be transfered to but can be used
165 root 1.104 to save the current coroutine state in (note that this is dangerous, as no
166     reference is taken to ensure that the "current coroutine state" survives,
167     the caller is responsible to ensure that the cloned state does not go
168     away).
169 root 1.1
170 root 1.55 The returned object is an empty hash which can be used for any purpose
171     whatsoever, for example when subclassing Coro::State.
172    
173 root 1.79 Certain variables are "localised" to each coroutine, that is, certain
174     "global" variables are actually per coroutine. Not everything that would
175     sensibly be localised currently is, and not everything that is localised
176     makes sense for every application, and the future might bring changes.
177 root 1.1
178 root 1.84 The following global variables can have different values per coroutine,
179     and have the stated initial values:
180 root 1.5
181 root 1.83 Variable Initial Value
182     @_ whatever arguments were passed to the Coro
183     $_ undef
184     $@ undef
185     $/ "\n"
186 root 1.88 $SIG{__DIE__} aliased to $Coro::State::DIEHOOK(*)
187     $SIG{__WARN__} aliased to $Coro::State::WARNHOOK(*)
188 root 1.83 (default fh) *STDOUT
189 root 1.84 $1, $2... all regex results are initially undefined
190 root 1.2
191 root 1.88 (*) reading the value from %SIG is not supported, but local'ising is.
192    
193 root 1.70 If you feel that something important is missing then tell me. Also
194 root 1.2 remember that every function call that might call C<transfer> (such
195     as C<Coro::Channel::put>) might clobber any global and/or special
196     variables. Yes, this is by design ;) You can always create your own
197     process abstraction model that saves these variables.
198 root 1.1
199 root 1.9 The easiest way to do this is to create your own scheduling primitive like
200 root 1.94 in the code below, and use it in your coroutines:
201 root 1.1
202 root 1.84 sub my_cede {
203 root 1.80 local ($;, ...);
204 root 1.84 Coro::cede;
205 root 1.1 }
206    
207 root 1.79 =cut
208    
209     # this is called for each newly created C coroutine,
210     # and is being artificially injected into the opcode flow.
211     # its sole purpose is to call transfer() once so it knows
212     # the stop level stack frame for stack sharing.
213     sub _cctx_init {
214     _set_stacklevel $_[0];
215     }
216    
217 root 1.76 =item $state->call ($coderef)
218    
219 root 1.94 Try to call the given C<$coderef> in the context of the given state. This
220 root 1.76 works even when the state is currently within an XS function, and can
221     be very dangerous. You can use it to acquire stack traces etc. (see the
222     Coro::Debug module for more details). The coderef MUST NOT EVER transfer
223     to another state.
224    
225     =item $state->eval ($string)
226    
227 root 1.94 Like C<call>, but eval's the string. Dangerous.
228 root 1.76
229 root 1.90 =item $state->throw ($exception)
230    
231     Makes the coroutine throw the given exception as soon as it regains
232 root 1.94 control.
233 root 1.90
234     =item $state->swap_defsv
235    
236     =item $state->swap_defav
237    
238     Swap the current C<$_> (swap_defsv) or C<@_> (swap_defav) with the
239     equivalent in the saved state of C<$state>. This can be used to give the
240     coroutine a defined content for C<@_> and C<$_> before transfer'ing to it.
241    
242 root 1.77 =item $state->trace ($flags)
243    
244     Internal function to control tracing. I just mention this so you can stay
245 root 1.90 away from abusing it.
246 root 1.77
247 root 1.70 =item $prev->transfer ($next)
248    
249     Save the state of the current subroutine in C<$prev> and switch to the
250     coroutine saved in C<$next>.
251    
252     The "state" of a subroutine includes the scope, i.e. lexical variables and
253     the current execution state (subroutine, stack).
254    
255 root 1.94 =item $state->has_cctx
256    
257 root 1.105 Returns whether the state currently uses a cctx/C coroutine. An active
258 root 1.94 state always has a cctx, as well as the main program. Other states only
259     use a cctxts when needed.
260    
261     =item $bytes = $state->rss
262    
263     Returns the memory allocated by the coroutine (which includes
264     static structures, various perl stacks but NOT local variables,
265     arguments or any C stack).
266    
267 root 1.64 =item Coro::State::cctx_count
268    
269     Returns the number of C-level coroutines allocated. If this number is
270     very high (more than a dozen) it might help to identify points of C-level
271     recursion in your code and moving this into a separate coroutine.
272    
273     =item Coro::State::cctx_idle
274    
275     Returns the number of allocated but idle (free for reuse) C level
276 root 1.76 coroutines. Currently, Coro will limit the number of idle/unused cctxs to
277     8.
278 root 1.64
279 root 1.72 =item Coro::State::cctx_stacksize [$new_stacksize]
280    
281     Returns the current C stack size and optionally sets the new I<minimum>
282     stack size to C<$new_stacksize> I<long>s. Existing stacks will not
283     be changed, but Coro will try to replace smaller stacks as soon as
284 root 1.91 possible. Any Coro::State that starts to use a stack after this call is
285 root 1.94 guaranteed this minimum stack size.
286    
287     Please note that Coroutines will only need to use a C-level stack if the
288     interpreter recurses or calls a function in a module that calls back into
289     the interpreter, so use of this feature is usually never needed.
290 root 1.72
291 root 1.92 =item Coro::State::force_cctx
292    
293     Forces the allocation of a C context for the currently running coroutine
294     (if not already done). Apart from benchmarking there is little point
295     in doing so, however.
296    
297 root 1.76 =item @states = Coro::State::list
298    
299     Returns a list of all states currently allocated.
300    
301 root 1.1 =cut
302    
303 root 1.75 sub debug_desc {
304     $_[0]{desc}
305     }
306    
307 root 1.1 1;
308    
309     =back
310    
311     =head1 BUGS
312    
313 root 1.5 This module is not thread-safe. You must only ever use this module from
314 root 1.94 the same thread (this requirement might be removed in the future).
315 root 1.1
316     =head1 SEE ALSO
317    
318     L<Coro>.
319    
320     =head1 AUTHOR
321    
322 root 1.41 Marc Lehmann <schmorp@schmorp.de>
323 root 1.39 http://home.schmorp.de/
324 root 1.1
325     =cut
326