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

Comparing Coro/README (file contents):
Revision 1.2 by root, Sat Aug 20 01:10:22 2005 UTC vs.
Revision 1.12 by root, Thu Oct 11 00:38:37 2007 UTC

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";
10 cede; # yield back to main
11 print "4\n";
9 }; 12 };
13 print "1\n";
14 cede; # yield to coroutine
15 print "3\n";
16 cede; # and again
10 17
11 # alternatively create an async process like this: 18 # use locking
19 my $lock = new Coro::Semaphore;
20 my $locked;
12 21
13 sub some_func : Coro { 22 $lock->down;
14 # some more async code 23 $locked = 1;
15 } 24 $lock->up;
16
17 cede;
18 25
19DESCRIPTION 26DESCRIPTION
20 This module collection manages coroutines. Coroutines are similar to 27 This module collection manages coroutines. Coroutines are similar to
21 threads but don't run in parallel. 28 threads but don't run in parallel at the same time even on SMP machines.
29 The specific flavor of coroutine used in this module also guarantees you
30 that it will not switch between coroutines unless necessary, at
31 easily-identified points in your program, so locking and parallel access
32 are rarely an issue, making coroutine programming much safer than
33 threads programming.
34
35 (Perl, however, does not natively support real threads but instead does
36 a very slow and memory-intensive emulation of processes using threads.
37 This is a performance win on Windows machines, and a loss everywhere
38 else).
22 39
23 In this module, coroutines are defined as "callchain + lexical variables 40 In this module, coroutines are defined as "callchain + lexical variables
24 + @_ + $_ + $@ + $^W + C stack), that is, a coroutine has it's own 41 + @_ + $_ + $@ + $/ + C stack), that is, a coroutine has its own
25 callchain, it's own set of lexicals and it's own set of perl's most 42 callchain, its own set of lexicals and its own set of perls most
26 important global variables. 43 important global variables (see Coro::State for more configuration).
27 44
28 $main 45 $main
29 This coroutine represents the main program. 46 This coroutine represents the main program.
30 47
31 $current (or as function: current) 48 $current (or as function: current)
32 The current coroutine (the last coroutine switched to). The initial 49 The current coroutine (the last coroutine switched to). The initial
33 value is $main (of course). 50 value is $main (of course).
34 51
52 This variable is strictly *read-only*. It is provided for
53 performance reasons. If performance is not essential you are
54 encouraged to use the "Coro::current" function instead.
55
35 $idle 56 $idle
36 The coroutine to switch to when no other coroutine is running. The 57 A callback that is called whenever the scheduler finds no ready
37 default implementation prints "FATAL: deadlock detected" and exits. 58 coroutines to run. The default implementation prints "FATAL:
59 deadlock detected" and exits, because the program has no other way
60 to continue.
61
62 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
64 coroutine so the scheduler can run it.
65
66 Please note that if your callback recursively invokes perl (e.g. for
67 event handlers), then it must be prepared to be called recursively
68 itself.
38 69
39 STATIC METHODS 70 STATIC METHODS
40 Static methods are actually functions that operate on the current 71 Static methods are actually functions that operate on the current
41 process only. 72 coroutine only.
42 73
43 async { ... } [@args...] 74 async { ... } [@args...]
44 Create a new asynchronous process and return it's process object 75 Create a new asynchronous coroutine and return it's coroutine object
45 (usually unused). When the sub returns the new process is 76 (usually unused). When the sub returns the new coroutine is
46 automatically terminated. 77 automatically terminated.
78
79 See the "Coro::State::new" constructor for info about the coroutine
80 environment in which coroutines run.
81
82 Calling "exit" in a coroutine will do the same as calling exit
83 outside the coroutine. Likewise, when the coroutine dies, the
84 program will exit, just as it would in the main program.
47 85
48 # create a new coroutine that just prints its arguments 86 # create a new coroutine that just prints its arguments
49 async { 87 async {
50 print "@_\n"; 88 print "@_\n";
51 } 1,2,3,4; 89 } 1,2,3,4;
52 90
91 async_pool { ... } [@args...]
92 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
94 coroutine that might have executed other code already (which can be
95 good or bad :).
96
97 Also, the block is executed in an "eval" context and a warning will
98 be issued in case of an exception instead of terminating the
99 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
101 terminate or cancel, which somehow defeats the purpose of pooling.
102
103 The priority will be reset to 0 after each job, tracing will be
104 disabled, the description will be reset and the default output
105 filehandle gets restored, so you can change alkl these. Otherwise
106 the coroutine will be re-used "as-is": most notably if you change
107 other per-coroutine global stuff such as $/ you need to revert that
108 change, which is most simply done by using local as in " local $/ ".
109
110 The pool size is limited to 8 idle coroutines (this can be adjusted
111 by changing $Coro::POOL_SIZE), and there can be as many non-idle
112 coros as required.
113
114 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.
116 "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
118 grows larger than 16kb (adjustable with $Coro::POOL_RSS) it will
119 also exit.
120
53 schedule 121 schedule
54 Calls the scheduler. Please note that the current process will not 122 Calls the scheduler. Please note that the current coroutine will not
55 be put into the ready queue, so calling this function usually means 123 be put into the ready queue, so calling this function usually means
56 you will never be called again. 124 you will never be called again unless something else (e.g. an event
125 handler) calls ready.
126
127 The canonical way to wait on external events is this:
128
129 {
130 # remember current coroutine
131 my $current = $Coro::current;
132
133 # register a hypothetical event handler
134 on_event_invoke sub {
135 # wake up sleeping coroutine
136 $current->ready;
137 undef $current;
138 };
139
140 # call schedule until event occurred.
141 # in case we are woken up for other reasons
142 # (current still defined), loop.
143 Coro::schedule while $current;
144 }
57 145
58 cede 146 cede
59 "Cede" to other processes. This function puts the current process 147 "Cede" to other coroutines. This function puts the current coroutine
60 into the ready queue and calls "schedule", which has the effect of 148 into the ready queue and calls "schedule", which has the effect of
61 giving up the current "timeslice" to other coroutines of the same or 149 giving up the current "timeslice" to other coroutines of the same or
62 higher priority. 150 higher priority.
63 151
152 Coro::cede_notself
153 Works like cede, but is not exported by default and will cede to any
154 coroutine, regardless of priority, once.
155
64 terminate [arg...] 156 terminate [arg...]
65 Terminates the current process with the given status values (see 157 Terminates the current coroutine with the given status values (see
66 cancel). 158 cancel).
67 159
160 killall
161 Kills/terminates/cancels all coroutines except the currently running
162 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.
164
68 # dynamic methods 165 # dynamic methods
69 166
70 PROCESS METHODS 167 COROUTINE METHODS
71 These are the methods you can call on process objects. 168 These are the methods you can call on coroutine objects.
72 169
73 new Coro \&sub [, @args...] 170 new Coro \&sub [, @args...]
74 Create a new process and return it. When the sub returns the process 171 Create a new coroutine and return it. When the sub returns the
75 automatically terminates as if "terminate" with the returned values 172 coroutine automatically terminates as if "terminate" with the
76 were called. To make the process run you must first put it into the 173 returned values were called. To make the coroutine run you must
77 ready queue by calling the ready method. 174 first put it into the ready queue by calling the ready method.
78 175
79 $process->ready 176 See "async" and "Coro::State::new" for additional info about the
177 coroutine environment.
178
179 $success = $coroutine->ready
80 Put the given process into the ready queue. 180 Put the given coroutine into the ready queue (according to it's
181 priority) and return true. If the coroutine is already in the ready
182 queue, do nothing and return false.
81 183
184 $is_ready = $coroutine->is_ready
185 Return wether the coroutine is currently the ready queue or not,
186
82 $process->cancel (arg...) 187 $coroutine->cancel (arg...)
83 Temrinates the given process and makes it return the given arguments 188 Terminates the given coroutine and makes it return the given
84 as status (default: the empty list). 189 arguments as status (default: the empty list). Never returns if the
190 coroutine is the current coroutine.
85 191
86 $process->join 192 $coroutine->join
87 Wait until the coroutine terminates and return any values given to 193 Wait until the coroutine terminates and return any values given to
88 the "terminate" or "cancel" functions. "join" can be called multiple 194 the "terminate" or "cancel" functions. "join" can be called
89 times from multiple processes. 195 concurrently from multiple coroutines.
90 196
197 $coroutine->on_destroy (\&cb)
198 Registers a callback that is called when this coroutine gets
199 destroyed, but before it is joined. The callback gets passed the
200 terminate arguments, if any.
201
91 $oldprio = $process->prio($newprio) 202 $oldprio = $coroutine->prio ($newprio)
92 Sets (or gets, if the argument is missing) the priority of the 203 Sets (or gets, if the argument is missing) the priority of the
93 process. Higher priority processes get run before lower priority 204 coroutine. Higher priority coroutines get run before lower priority
94 processes. Priorities are small signed integers (currently -4 .. 205 coroutines. Priorities are small signed integers (currently -4 ..
95 +3), that you can refer to using PRIO_xxx constants (use the import 206 +3), that you can refer to using PRIO_xxx constants (use the import
96 tag :prio to get then): 207 tag :prio to get then):
97 208
98 PRIO_MAX > PRIO_HIGH > PRIO_NORMAL > PRIO_LOW > PRIO_IDLE > PRIO_MIN 209 PRIO_MAX > PRIO_HIGH > PRIO_NORMAL > PRIO_LOW > PRIO_IDLE > PRIO_MIN
99 3 > 1 > 0 > -1 > -3 > -4 210 3 > 1 > 0 > -1 > -3 > -4
102 current->prio(PRIO_HIGH); 213 current->prio(PRIO_HIGH);
103 214
104 The idle coroutine ($Coro::idle) always has a lower priority than 215 The idle coroutine ($Coro::idle) always has a lower priority than
105 any existing coroutine. 216 any existing coroutine.
106 217
107 Changing the priority of the current process will take effect 218 Changing the priority of the current coroutine will take effect
108 immediately, but changing the priority of processes in the ready 219 immediately, but changing the priority of coroutines in the ready
109 queue (but not running) will only take effect after the next 220 queue (but not running) will only take effect after the next
110 schedule (of that process). This is a bug that will be fixed in some 221 schedule (of that coroutine). This is a bug that will be fixed in
111 future version. 222 some future version.
112 223
113 $newprio = $process->nice($change) 224 $newprio = $coroutine->nice ($change)
114 Similar to "prio", but subtract the given value from the priority 225 Similar to "prio", but subtract the given value from the priority
115 (i.e. higher values mean lower priority, just as in unix). 226 (i.e. higher values mean lower priority, just as in unix).
116 227
117 $olddesc = $process->desc($newdesc) 228 $olddesc = $coroutine->desc ($newdesc)
118 Sets (or gets in case the argument is missing) the description for 229 Sets (or gets in case the argument is missing) the description for
119 this process. This is just a free-form string you can associate with 230 this coroutine. This is just a free-form string you can associate
120 a process. 231 with a coroutine.
232
233 This method simply sets the "$coroutine->{desc}" member to the given
234 string. You can modify this member directly if you wish.
235
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
252 Coro::nready
253 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
255 runnable coroutine is the currently running one, so "cede" would
256 have no effect, and "schedule" would cause a deadlock unless there
257 is an idle handler that wakes up some coroutines.
258
259 my $guard = Coro::guard { ... }
260 This creates and returns a guard object. Nothing happens until the
261 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
263 case of a runtime error or when the coroutine gets canceled, as in
264 both cases the guard block will be executed. The guard object
265 supports only one method, "->cancel", which will keep the codeblock
266 from being executed.
267
268 Example: set some flag and clear it again when the coroutine gets
269 canceled or the function returns:
270
271 sub do_something {
272 my $guard = Coro::guard { $busy = 0 };
273 $busy = 1;
274
275 # do something that requires $busy to be true
276 }
277
278 unblock_sub { ... }
279 This utility function takes a BLOCK or code reference and "unblocks"
280 it, returning the new coderef. This means that the new coderef will
281 return immediately without blocking, returning nothing, while the
282 original code ref will be called (with parameters) from within its
283 own coroutine.
284
285 The reason this function exists is that many event libraries (such
286 as the venerable Event module) are not coroutine-safe (a weaker form
287 of thread-safety). This means you must not block within event
288 callbacks, otherwise you might suffer from crashes or worse.
289
290 This function allows your callbacks to block by executing them in
291 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
293 results to disk.
294
295 In short: simply use "unblock_sub { ... }" instead of "sub { ... }"
296 when creating event callbacks that want to block.
121 297
122BUGS/LIMITATIONS 298BUGS/LIMITATIONS
123 - you must make very sure that no coro is still active on global 299 - you must make very sure that no coro is still active on global
124 destruction. very bad things might happen otherwise (usually segfaults). 300 destruction. very bad things might happen otherwise (usually segfaults).
125 301
126 - this module is not thread-safe. You should only ever use this module 302 - this module is not thread-safe. You should only ever use this module
127 from the same thread (this requirement might be losened in the future 303 from the same thread (this requirement might be loosened in the future
128 to allow per-thread schedulers, but Coro::State does not yet allow 304 to allow per-thread schedulers, but Coro::State does not yet allow
129 this). 305 this).
130 306
131SEE ALSO 307SEE ALSO
308 Lower level Configuration, Coroutine Environment: Coro::State.
309
310 Debugging: Coro::Debug.
311
132 Support/Utility: Coro::Cont, Coro::Specific, Coro::State, Coro::Util. 312 Support/Utility: Coro::Specific, Coro::Util.
133 313
134 Locking/IPC: Coro::Signal, Coro::Channel, Coro::Semaphore, 314 Locking/IPC: Coro::Signal, Coro::Channel, Coro::Semaphore,
135 Coro::SemaphoreSet, Coro::RWLock. 315 Coro::SemaphoreSet, Coro::RWLock.
136 316
137 Event/IO: Coro::Timer, Coro::Event, Coro::Handle, Coro::Socket, 317 Event/IO: Coro::Timer, Coro::Event, Coro::Handle, Coro::Socket.
138 Coro::Select.
139 318
319 Compatibility: Coro::LWP, Coro::Storable, Coro::Select.
320
140 Embedding: <Coro:MakeMaker> 321 Embedding: <Coro:MakeMaker>.
141 322
142AUTHOR 323AUTHOR
143 Marc Lehmann <schmorp@schmorp.de> 324 Marc Lehmann <schmorp@schmorp.de>
144 http://home.schmorp.de/ 325 http://home.schmorp.de/
145 326

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines