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

Comparing Coro/README (file contents):
Revision 1.12 by root, Thu Oct 11 00:38:37 2007 UTC vs.
Revision 1.17 by root, Wed Nov 5 15:38:10 2008 UTC

1NAME 1NAME
2 Coro - coroutine process abstraction 2 Coro - coroutine process abstraction
3 3
4SYNOPSIS 4SYNOPSIS
5 use Coro; 5 use Coro;
6 6
7 async { 7 async {
8 # some asynchronous thread of execution 8 # some asynchronous thread of execution
9 print "2\n"; 9 print "2\n";
10 cede; # yield back to main 10 cede; # yield back to main
11 print "4\n"; 11 print "4\n";
12 }; 12 };
13 print "1\n"; 13 print "1\n";
14 cede; # yield to coroutine 14 cede; # yield to coroutine
15 print "3\n"; 15 print "3\n";
16 cede; # and again 16 cede; # and again
17 17
18 # use locking 18 # use locking
19 use Coro::Semaphore;
19 my $lock = new Coro::Semaphore; 20 my $lock = new Coro::Semaphore;
20 my $locked; 21 my $locked;
21 22
22 $lock->down; 23 $lock->down;
23 $locked = 1; 24 $locked = 1;
24 $lock->up; 25 $lock->up;
25 26
26DESCRIPTION 27DESCRIPTION
27 This module collection manages coroutines. Coroutines are similar to 28 This module collection manages coroutines. Coroutines are similar to
28 threads but don't run in parallel at the same time even on SMP machines. 29 threads but don't (in general) run in parallel at the same time even on
29 The specific flavor of coroutine used in this module also guarantees you 30 SMP machines. The specific flavor of coroutine used in this module also
30 that it will not switch between coroutines unless necessary, at 31 guarantees you that it will not switch between coroutines unless
31 easily-identified points in your program, so locking and parallel access 32 necessary, at easily-identified points in your program, so locking and
32 are rarely an issue, making coroutine programming much safer than 33 parallel access are rarely an issue, making coroutine programming much
33 threads programming. 34 safer and easier than threads programming.
34 35
35 (Perl, however, does not natively support real threads but instead does 36 Unlike a normal perl program, however, coroutines allow you to have
36 a very slow and memory-intensive emulation of processes using threads. 37 multiple running interpreters that share data, which is especially
37 This is a performance win on Windows machines, and a loss everywhere 38 useful to code pseudo-parallel processes and for event-based
38 else). 39 programming, such as multiple HTTP-GET requests running concurrently.
40 See Coro::AnyEvent to learn more.
41
42 Coroutines are also useful because Perl has no support for threads (the
43 so called "threads" that perl offers are nothing more than the (bad)
44 process emulation coming from the Windows platform: On standard
45 operating systems they serve no purpose whatsoever, except by making
46 your programs slow and making them use a lot of memory. Best disable
47 them when building perl, or aks your software vendor/distributor to do
48 it for you).
39 49
40 In this module, coroutines are defined as "callchain + lexical variables 50 In this module, coroutines are defined as "callchain + lexical variables
41 + @_ + $_ + $@ + $/ + C stack), that is, a coroutine has its own 51 + @_ + $_ + $@ + $/ + C stack), that is, a coroutine has its own
42 callchain, its own set of lexicals and its own set of perls most 52 callchain, its own set of lexicals and its own set of perls most
43 important global variables (see Coro::State for more configuration). 53 important global variables (see Coro::State for more configuration).
44 54
45 $main 55 $Coro::main
46 This coroutine represents the main program. 56 This variable stores the coroutine object that represents the main
57 program. While you cna "ready" it and do most other things you can
58 do to coroutines, it is mainly useful to compare again
59 $Coro::current, to see whether you are running in the main program
60 or not.
47 61
48 $current (or as function: current) 62 $Coro::current
49 The current coroutine (the last coroutine switched to). The initial 63 The coroutine object representing the current coroutine (the last
64 coroutine that the Coro scheduler switched to). The initial value is
50 value is $main (of course). 65 $main (of course).
51 66
52 This variable is strictly *read-only*. It is provided for 67 This variable is strictly *read-only*. You can take copies of the
53 performance reasons. If performance is not essential you are 68 value stored in it and use it as any other coroutine object, but you
54 encouraged to use the "Coro::current" function instead. 69 must not otherwise modify the variable itself.
55 70
56 $idle 71 $Coro::idle
57 A callback that is called whenever the scheduler finds no ready 72 This variable is mainly useful to integrate Coro into event loops.
58 coroutines to run. The default implementation prints "FATAL: 73 It is usually better to rely on Coro::AnyEvent or L"Coro::EV", as
59 deadlock detected" and exits, because the program has no other way 74 this is pretty low-level functionality.
60 to continue. 75
76 This variable stores a callback that is called whenever the
77 scheduler finds no ready coroutines to run. The default
78 implementation prints "FATAL: deadlock detected" and exits, because
79 the program has no other way to continue.
61 80
62 This hook is overwritten by modules such as "Coro::Timer" and 81 This hook is overwritten by modules such as "Coro::Timer" and
63 "Coro::Event" to wait on an external event that hopefully wake up a 82 "Coro::AnyEvent" to wait on an external event that hopefully wake up
64 coroutine so the scheduler can run it. 83 a coroutine so the scheduler can run it.
84
85 Note that the callback *must not*, under any circumstances, block
86 the current coroutine. Normally, this is achieved by having an "idle
87 coroutine" that calls the event loop and then blocks again, and then
88 readying that coroutine in the idle handler.
89
90 See Coro::Event or Coro::AnyEvent for examples of using this
91 technique.
65 92
66 Please note that if your callback recursively invokes perl (e.g. for 93 Please note that if your callback recursively invokes perl (e.g. for
67 event handlers), then it must be prepared to be called recursively 94 event handlers), then it must be prepared to be called recursively
68 itself. 95 itself.
69 96
70 STATIC METHODS 97 SIMPLE COROUTINE CREATION
71 Static methods are actually functions that operate on the current
72 coroutine only.
73
74 async { ... } [@args...] 98 async { ... } [@args...]
75 Create a new asynchronous coroutine and return it's coroutine object 99 Create a new coroutine and return it's coroutine object (usually
76 (usually unused). When the sub returns the new coroutine is 100 unused). The coroutine will be put into the ready queue, so it will
101 start running automatically on the next scheduler run.
102
103 The first argument is a codeblock/closure that should be executed in
104 the coroutine. When it returns argument returns the coroutine is
77 automatically terminated. 105 automatically terminated.
78 106
107 The remaining arguments are passed as arguments to the closure.
108
79 See the "Coro::State::new" constructor for info about the coroutine 109 See the "Coro::State::new" constructor for info about the coroutine
80 environment in which coroutines run. 110 environment in which coroutines are executed.
81 111
82 Calling "exit" in a coroutine will do the same as calling exit 112 Calling "exit" in a coroutine will do the same as calling exit
83 outside the coroutine. Likewise, when the coroutine dies, the 113 outside the coroutine. Likewise, when the coroutine dies, the
84 program will exit, just as it would in the main program. 114 program will exit, just as it would in the main program.
85 115
116 If you do not want that, you can provide a default "die" handler, or
117 simply avoid dieing (by use of "eval").
118
86 # create a new coroutine that just prints its arguments 119 Example: Create a new coroutine that just prints its arguments.
120
87 async { 121 async {
88 print "@_\n"; 122 print "@_\n";
89 } 1,2,3,4; 123 } 1,2,3,4;
90 124
91 async_pool { ... } [@args...] 125 async_pool { ... } [@args...]
92 Similar to "async", but uses a coroutine pool, so you should not 126 Similar to "async", but uses a coroutine pool, so you should not
93 call terminate or join (although you are allowed to), and you get a 127 call terminate or join on it (although you are allowed to), and you
94 coroutine that might have executed other code already (which can be 128 get a coroutine that might have executed other code already (which
95 good or bad :). 129 can be good or bad :).
96 130
131 On the plus side, this function is faster than creating (and
132 destroying) a completly new coroutine, so if you need a lot of
133 generic coroutines in quick successsion, use "async_pool", not
134 "async".
135
97 Also, the block is executed in an "eval" context and a warning will 136 The code block is executed in an "eval" context and a warning will
98 be issued in case of an exception instead of terminating the 137 be issued in case of an exception instead of terminating the
99 program, as "async" does. As the coroutine is being reused, stuff 138 program, as "async" does. As the coroutine is being reused, stuff
100 like "on_destroy" will not work in the expected way, unless you call 139 like "on_destroy" will not work in the expected way, unless you call
101 terminate or cancel, which somehow defeats the purpose of pooling. 140 terminate or cancel, which somehow defeats the purpose of pooling
141 (but is fine in the exceptional case).
102 142
103 The priority will be reset to 0 after each job, tracing will be 143 The priority will be reset to 0 after each run, tracing will be
104 disabled, the description will be reset and the default output 144 disabled, the description will be reset and the default output
105 filehandle gets restored, so you can change alkl these. Otherwise 145 filehandle gets restored, so you can change all these. Otherwise the
106 the coroutine will be re-used "as-is": most notably if you change 146 coroutine will be re-used "as-is": most notably if you change other
107 other per-coroutine global stuff such as $/ you need to revert that 147 per-coroutine global stuff such as $/ you *must needs* revert that
108 change, which is most simply done by using local as in " local $/ ". 148 change, which is most simply done by using local as in: "local $/".
109 149
110 The pool size is limited to 8 idle coroutines (this can be adjusted 150 The idle pool size is limited to 8 idle coroutines (this can be
111 by changing $Coro::POOL_SIZE), and there can be as many non-idle 151 adjusted by changing $Coro::POOL_SIZE), but there can be as many
112 coros as required. 152 non-idle coros as required.
113 153
114 If you are concerned about pooled coroutines growing a lot because a 154 If you are concerned about pooled coroutines growing a lot because a
115 single "async_pool" used a lot of stackspace you can e.g. 155 single "async_pool" used a lot of stackspace you can e.g.
116 "async_pool { terminate }" once per second or so to slowly replenish 156 "async_pool { terminate }" once per second or so to slowly replenish
117 the pool. In addition to that, when the stacks used by a handler 157 the pool. In addition to that, when the stacks used by a handler
118 grows larger than 16kb (adjustable with $Coro::POOL_RSS) it will 158 grows larger than 16kb (adjustable via $Coro::POOL_RSS) it will also
119 also exit. 159 be destroyed.
160
161 STATIC METHODS
162 Static methods are actually functions that operate on the current
163 coroutine.
120 164
121 schedule 165 schedule
122 Calls the scheduler. Please note that the current coroutine will not 166 Calls the scheduler. The scheduler will find the next coroutine that
167 is to be run from the ready queue and switches to it. The next
168 coroutine to be run is simply the one with the highest priority that
169 is longest in its ready queue. If there is no coroutine ready, it
170 will clal the $Coro::idle hook.
171
172 Please note that the current coroutine will *not* be put into the
123 be put into the ready queue, so calling this function usually means 173 ready queue, so calling this function usually means you will never
124 you will never be called again unless something else (e.g. an event 174 be called again unless something else (e.g. an event handler) calls
125 handler) calls ready. 175 "->ready", thus waking you up.
176
177 This makes "schedule" *the* generic method to use to block the
178 current coroutine and wait for events: first you remember the
179 current coroutine in a variable, then arrange for some callback of
180 yours to call "->ready" on that once some event happens, and last
181 you call "schedule" to put yourself to sleep. Note that a lot of
182 things can wake your coroutine up, so you need to check whether the
183 event indeed happened, e.g. by storing the status in a variable.
126 184
127 The canonical way to wait on external events is this: 185 The canonical way to wait on external events is this:
128 186
129 { 187 {
130 # remember current coroutine 188 # remember current coroutine
145 203
146 cede 204 cede
147 "Cede" to other coroutines. This function puts the current coroutine 205 "Cede" to other coroutines. This function puts the current coroutine
148 into the ready queue and calls "schedule", which has the effect of 206 into the ready queue and calls "schedule", which has the effect of
149 giving up the current "timeslice" to other coroutines of the same or 207 giving up the current "timeslice" to other coroutines of the same or
150 higher priority. 208 higher priority. Once your coroutine gets its turn again it will
209 automatically be resumed.
210
211 This function is often called "yield" in other languages.
151 212
152 Coro::cede_notself 213 Coro::cede_notself
153 Works like cede, but is not exported by default and will cede to any 214 Works like cede, but is not exported by default and will cede to
154 coroutine, regardless of priority, once. 215 *any* coroutine, regardless of priority. This is useful sometimes to
216 ensure progress is made.
155 217
156 terminate [arg...] 218 terminate [arg...]
157 Terminates the current coroutine with the given status values (see 219 Terminates the current coroutine with the given status values (see
158 cancel). 220 cancel).
159 221
160 killall 222 killall
161 Kills/terminates/cancels all coroutines except the currently running 223 Kills/terminates/cancels all coroutines except the currently running
162 one. This is useful after a fork, either in the child or the parent, 224 one. This is useful after a fork, either in the child or the parent,
163 as usually only one of them should inherit the running coroutines. 225 as usually only one of them should inherit the running coroutines.
164 226
165 # dynamic methods 227 Note that while this will try to free some of the main programs
228 resources, you cannot free all of them, so if a coroutine that is
229 not the main program calls this function, there will be some
230 one-time resource leak.
166 231
167 COROUTINE METHODS 232 COROUTINE METHODS
168 These are the methods you can call on coroutine objects. 233 These are the methods you can call on coroutine objects (or to create
234 them).
169 235
170 new Coro \&sub [, @args...] 236 new Coro \&sub [, @args...]
171 Create a new coroutine and return it. When the sub returns the 237 Create a new coroutine and return it. When the sub returns, the
172 coroutine automatically terminates as if "terminate" with the 238 coroutine automatically terminates as if "terminate" with the
173 returned values were called. To make the coroutine run you must 239 returned values were called. To make the coroutine run you must
174 first put it into the ready queue by calling the ready method. 240 first put it into the ready queue by calling the ready method.
175 241
176 See "async" and "Coro::State::new" for additional info about the 242 See "async" and "Coro::State::new" for additional info about the
177 coroutine environment. 243 coroutine environment.
178 244
179 $success = $coroutine->ready 245 $success = $coroutine->ready
180 Put the given coroutine into the ready queue (according to it's 246 Put the given coroutine into the end of its ready queue (there is
181 priority) and return true. If the coroutine is already in the ready 247 one queue for each priority) and return true. If the coroutine is
182 queue, do nothing and return false. 248 already in the ready queue, do nothing and return false.
249
250 This ensures that the scheduler will resume this coroutine
251 automatically once all the coroutines of higher priority and all
252 coroutines of the same priority that were put into the ready queue
253 earlier have been resumed.
183 254
184 $is_ready = $coroutine->is_ready 255 $is_ready = $coroutine->is_ready
185 Return wether the coroutine is currently the ready queue or not, 256 Return whether the coroutine is currently the ready queue or not,
186 257
187 $coroutine->cancel (arg...) 258 $coroutine->cancel (arg...)
188 Terminates the given coroutine and makes it return the given 259 Terminates the given coroutine and makes it return the given
189 arguments as status (default: the empty list). Never returns if the 260 arguments as status (default: the empty list). Never returns if the
190 coroutine is the current coroutine. 261 coroutine is the current coroutine.
191 262
263 $coroutine->throw ([$scalar])
264 If $throw is specified and defined, it will be thrown as an
265 exception inside the coroutine at the next convenient point in time
266 (usually after it gains control at the next schedule/transfer/cede).
267 Otherwise clears the exception object.
268
269 The exception object will be thrown "as is" with the specified
270 scalar in $@, i.e. if it is a string, no line number or newline will
271 be appended (unlike with "die").
272
273 This can be used as a softer means than "cancel" to ask a coroutine
274 to end itself, although there is no guarantee that the exception
275 will lead to termination, and if the exception isn't caught it might
276 well end the whole program.
277
278 You might also think of "throw" as being the moral equivalent of
279 "kill"ing a coroutine with a signal (in this case, a scalar).
280
192 $coroutine->join 281 $coroutine->join
193 Wait until the coroutine terminates and return any values given to 282 Wait until the coroutine terminates and return any values given to
194 the "terminate" or "cancel" functions. "join" can be called 283 the "terminate" or "cancel" functions. "join" can be called
195 concurrently from multiple coroutines. 284 concurrently from multiple coroutines, and all will be resumed and
285 given the status return once the $coroutine terminates.
196 286
197 $coroutine->on_destroy (\&cb) 287 $coroutine->on_destroy (\&cb)
198 Registers a callback that is called when this coroutine gets 288 Registers a callback that is called when this coroutine gets
199 destroyed, but before it is joined. The callback gets passed the 289 destroyed, but before it is joined. The callback gets passed the
200 terminate arguments, if any. 290 terminate arguments, if any, and *must not* die, under any
291 circumstances.
201 292
202 $oldprio = $coroutine->prio ($newprio) 293 $oldprio = $coroutine->prio ($newprio)
203 Sets (or gets, if the argument is missing) the priority of the 294 Sets (or gets, if the argument is missing) the priority of the
204 coroutine. Higher priority coroutines get run before lower priority 295 coroutine. Higher priority coroutines get run before lower priority
205 coroutines. Priorities are small signed integers (currently -4 .. 296 coroutines. Priorities are small signed integers (currently -4 ..
231 with a coroutine. 322 with a coroutine.
232 323
233 This method simply sets the "$coroutine->{desc}" member to the given 324 This method simply sets the "$coroutine->{desc}" member to the given
234 string. You can modify this member directly if you wish. 325 string. You can modify this member directly if you wish.
235 326
236 $coroutine->throw ([$scalar])
237 If $throw is specified and defined, it will be thrown as an
238 exception inside the coroutine at the next convinient point in time
239 (usually after it gains control at the next schedule/transfer/cede).
240 Otherwise clears the exception object.
241
242 The exception object will be thrown "as is" with the specified
243 scalar in $@, i.e. if it is a string, no line number or newline will
244 be appended (unlike with "die").
245
246 This can be used as a softer means than "cancel" to ask a coroutine
247 to end itself, although there is no guarentee that the exception
248 will lead to termination, and if the exception isn't caught it might
249 well end the whole program.
250
251 GLOBAL FUNCTIONS 327 GLOBAL FUNCTIONS
252 Coro::nready 328 Coro::nready
253 Returns the number of coroutines that are currently in the ready 329 Returns the number of coroutines that are currently in the ready
254 state, i.e. that can be switched to. The value 0 means that the only 330 state, i.e. that can be switched to by calling "schedule" directory
255 runnable coroutine is the currently running one, so "cede" would 331 or indirectly. The value 0 means that the only runnable coroutine is
256 have no effect, and "schedule" would cause a deadlock unless there 332 the currently running one, so "cede" would have no effect, and
333 "schedule" would cause a deadlock unless there is an idle handler
257 is an idle handler that wakes up some coroutines. 334 that wakes up some coroutines.
258 335
259 my $guard = Coro::guard { ... } 336 my $guard = Coro::guard { ... }
260 This creates and returns a guard object. Nothing happens until the 337 This creates and returns a guard object. Nothing happens until the
261 object gets destroyed, in which case the codeblock given as argument 338 object gets destroyed, in which case the codeblock given as argument
262 will be executed. This is useful to free locks or other resources in 339 will be executed. This is useful to free locks or other resources in
275 # do something that requires $busy to be true 352 # do something that requires $busy to be true
276 } 353 }
277 354
278 unblock_sub { ... } 355 unblock_sub { ... }
279 This utility function takes a BLOCK or code reference and "unblocks" 356 This utility function takes a BLOCK or code reference and "unblocks"
280 it, returning the new coderef. This means that the new coderef will 357 it, returning a new coderef. Unblocking means that calling the new
281 return immediately without blocking, returning nothing, while the 358 coderef will return immediately without blocking, returning nothing,
282 original code ref will be called (with parameters) from within its 359 while the original code ref will be called (with parameters) from
283 own coroutine. 360 within another coroutine.
284 361
285 The reason this function exists is that many event libraries (such 362 The reason this function exists is that many event libraries (such
286 as the venerable Event module) are not coroutine-safe (a weaker form 363 as the venerable Event module) are not coroutine-safe (a weaker form
287 of thread-safety). This means you must not block within event 364 of thread-safety). This means you must not block within event
288 callbacks, otherwise you might suffer from crashes or worse. 365 callbacks, otherwise you might suffer from crashes or worse. The
366 only event library currently known that is safe to use without
367 "unblock_sub" is EV.
289 368
290 This function allows your callbacks to block by executing them in 369 This function allows your callbacks to block by executing them in
291 another coroutine where it is safe to block. One example where 370 another coroutine where it is safe to block. One example where
292 blocking is handy is when you use the Coro::AIO functions to save 371 blocking is handy is when you use the Coro::AIO functions to save
293 results to disk. 372 results to disk, for example.
294 373
295 In short: simply use "unblock_sub { ... }" instead of "sub { ... }" 374 In short: simply use "unblock_sub { ... }" instead of "sub { ... }"
296 when creating event callbacks that want to block. 375 when creating event callbacks that want to block.
297 376
377 If your handler does not plan to block (e.g. simply sends a message
378 to another coroutine, or puts some other coroutine into the ready
379 queue), there is no reason to use "unblock_sub".
380
381 Note that you also need to use "unblock_sub" for any other callbacks
382 that are indirectly executed by any C-based event loop. For example,
383 when you use a module that uses AnyEvent (and you use
384 Coro::AnyEvent) and it provides callbacks that are the result of
385 some event callback, then you must not block either, or use
386 "unblock_sub".
387
298BUGS/LIMITATIONS 388BUGS/LIMITATIONS
299 - you must make very sure that no coro is still active on global
300 destruction. very bad things might happen otherwise (usually segfaults).
301
302 - this module is not thread-safe. You should only ever use this module 389 This module is not perl-pseudo-thread-safe. You should only ever use
303 from the same thread (this requirement might be loosened in the future 390 this module from the same thread (this requirement might be removed in
304 to allow per-thread schedulers, but Coro::State does not yet allow 391 the future to allow per-thread schedulers, but Coro::State does not yet
305 this). 392 allow this). I recommend disabling thread support and using processes,
393 as this is much faster and uses less memory.
306 394
307SEE ALSO 395SEE ALSO
308 Lower level Configuration, Coroutine Environment: Coro::State. 396 Event-Loop integration: Coro::AnyEvent, Coro::EV, Coro::Event.
309 397
310 Debugging: Coro::Debug. 398 Debugging: Coro::Debug.
311 399
312 Support/Utility: Coro::Specific, Coro::Util. 400 Support/Utility: Coro::Specific, Coro::Util.
313 401
314 Locking/IPC: Coro::Signal, Coro::Channel, Coro::Semaphore, 402 Locking/IPC: Coro::Signal, Coro::Channel, Coro::Semaphore,
315 Coro::SemaphoreSet, Coro::RWLock. 403 Coro::SemaphoreSet, Coro::RWLock.
316 404
317 Event/IO: Coro::Timer, Coro::Event, Coro::Handle, Coro::Socket. 405 IO/Timers: Coro::Timer, Coro::Handle, Coro::Socket, Coro::AIO.
318 406
319 Compatibility: Coro::LWP, Coro::Storable, Coro::Select. 407 Compatibility: Coro::LWP, Coro::BDB, Coro::Storable, Coro::Select.
320 408
321 Embedding: <Coro:MakeMaker>. 409 XS API: Coro::MakeMaker.
410
411 Low level Configuration, Coroutine Environment: Coro::State.
322 412
323AUTHOR 413AUTHOR
324 Marc Lehmann <schmorp@schmorp.de> 414 Marc Lehmann <schmorp@schmorp.de>
325 http://home.schmorp.de/ 415 http://home.schmorp.de/
326 416

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines