]> git.lizzy.rs Git - rust.git/blob - src/libcore/task.rs
change spawn_connected argument to copy mode
[rust.git] / src / libcore / task.rs
1 /*
2 Module: task
3
4 Task management.
5
6 An executing Rust program consists of a tree of tasks, each with their own
7 stack, and sole ownership of their allocated heap data. Tasks communicate
8 with each other using ports and channels.
9
10 When a task fails, that failure will propagate to its parent (the task
11 that spawned it) and the parent will fail as well. The reverse is not
12 true: when a parent task fails its children will continue executing. When
13 the root (main) task fails, all tasks fail, and then so does the entire
14 process.
15
16 A task may remove itself from this failure propagation mechanism by
17 calling the <unsupervise> function, after which failure will only
18 result in the termination of that task.
19
20 Tasks may execute in parallel and are scheduled automatically by the runtime.
21
22 Example:
23
24 > spawn {||
25 >   log(debug, "Hello, World!");
26 > };
27
28 */
29 import cast = unsafe::reinterpret_cast;
30 import comm;
31 import ptr;
32 import c = ctypes;
33
34 export task;
35 export joinable_task;
36 export sleep;
37 export yield;
38 export task_notification;
39 export join;
40 export unsupervise;
41 export pin;
42 export unpin;
43 export task_result;
44 export tr_success;
45 export tr_failure;
46 export get_task;
47 export spawn;
48 export spawn_joinable;
49 export spawn_connected;
50 export connected_fn;
51 export connected_task;
52
53 #[abi = "rust-intrinsic"]
54 native mod rusti {
55     // these must run on the Rust stack so that they can swap stacks etc:
56     fn task_sleep(task: *rust_task, time_in_us: uint, &killed: bool);
57 }
58
59 type rust_closure = {
60     fnptr: c::intptr_t, envptr: c::intptr_t
61 };
62
63 #[link_name = "rustrt"]
64 #[abi = "cdecl"]
65 native mod rustrt {
66     // these can run on the C stack:
67     fn pin_task();
68     fn unpin_task();
69     fn get_task_id() -> task_id;
70     fn rust_get_task() -> *rust_task;
71
72     fn new_task() -> task_id;
73     fn drop_task(task_id: *rust_task);
74     fn get_task_pointer(id: task_id) -> *rust_task;
75
76     fn migrate_alloc(alloc: *u8, target: task_id);
77
78     fn start_task(id: task, closure: *rust_closure);
79 }
80
81 /* Section: Types */
82
83 type rust_task =
84     {id: task,
85      mutable notify_enabled: int,
86      mutable notify_chan: comm::chan<task_notification>,
87      mutable stack_ptr: *u8};
88
89 resource rust_task_ptr(task: *rust_task) { rustrt::drop_task(task); }
90
91 type task_id = int;
92
93 /*
94 Type: task
95
96 A handle to a task
97 */
98 type task = task_id;
99
100 /*
101 Function: spawn
102
103 Creates and executes a new child task
104
105 Sets up a new task with its own call stack and schedules it to be
106 executed.  Upon execution, the closure `f()` will be invoked.
107
108 Parameters:
109
110 f - A function to execute in the new task
111
112 Returns:
113
114 A handle to the new task
115 */
116 fn spawn(+f: sendfn()) -> task {
117     spawn_inner(f, none)
118 }
119
120 fn spawn_inner(-f: sendfn(),
121                notify: option<comm::chan<task_notification>>) -> task unsafe {
122     let closure: *rust_closure = unsafe::reinterpret_cast(ptr::addr_of(f));
123     #debug("spawn: closure={%x,%x}", (*closure).fnptr, (*closure).envptr);
124     let id = rustrt::new_task();
125
126     // set up notifications if they are enabled.
127     option::may(notify) {|c|
128         let task_ptr <- rust_task_ptr(rustrt::get_task_pointer(id));
129         (**task_ptr).notify_enabled = 1;
130         (**task_ptr).notify_chan = c;
131     }
132
133     rustrt::start_task(id, closure);
134     unsafe::leak(f);
135     ret id;
136 }
137
138 /*
139 Type: joinable_task
140
141 A task that sends notification upon termination
142 */
143 type joinable_task = (task, comm::port<task_notification>);
144
145 fn spawn_joinable(+f: sendfn()) -> joinable_task {
146     let notify_port = comm::port();
147     let notify_chan = comm::chan(notify_port);
148     let task = spawn_inner(f, some(notify_chan));
149     ret (task, notify_port);
150     /*
151     resource notify_rsrc(data: (comm::chan<task_notification>,
152                                 task,
153                                 @mutable task_result)) {
154         let (chan, task, tr) = data;
155         let msg = exit(task, *tr);
156         comm::send(chan, msg);
157     }
158
159     let notify_port = comm::port();
160     let notify_chan = comm::chan(notify_port);
161     let g = sendfn[copy notify_chan; move f]() {
162         let this_task = rustrt::get_task_id();
163         let result = @mutable tr_failure;
164         let _rsrc = notify_rsrc((notify_chan, this_task, result));
165         f();
166         *result = tr_success; // rsrc will fire msg when fn returns
167     };
168     let task = spawn(g);
169     ret (task, notify_port);
170     */
171 }
172
173 /*
174 Tag: task_result
175
176 Indicates the manner in which a task exited
177 */
178 tag task_result {
179     /* Variant: tr_success */
180     tr_success;
181     /* Variant: tr_failure */
182     tr_failure;
183 }
184
185 /*
186 Tag: task_notification
187
188 Message sent upon task exit to indicate normal or abnormal termination
189 */
190 tag task_notification {
191     /* Variant: exit */
192     exit(task, task_result);
193 }
194
195 /*
196 Type: connected_fn
197
198 The prototype for a connected child task function.  Such a function will be
199 supplied with a channel to send messages to the parent and a port to receive
200 messages from the parent. The type parameter `ToCh` is the type for messages
201 sent from the parent to the child and `FrCh` is the type for messages sent
202 from the child to the parent. */
203 type connected_fn<ToCh, FrCh> = sendfn(comm::port<ToCh>, comm::chan<FrCh>);
204
205 /*
206 Type: connected_fn
207
208 The result type of <spawn_connected>
209 */
210 type connected_task<ToCh, FrCh> = {
211     from_child: comm::port<FrCh>,
212     to_child: comm::chan<ToCh>,
213     task: task
214 };
215
216 /*
217 Function: spawn_connected
218
219 Spawns a child task along with a port/channel for exchanging messages
220 with the parent task.  The type `ToCh` represents messages sent to the child
221 and `FrCh` messages received from the child.
222
223 Parameters:
224
225 f - the child function to execute
226
227 Returns:
228
229 The new child task along with the port to receive messages and the channel
230 to send messages.
231 */
232 fn spawn_connected<ToCh:send, FrCh:send>(+f: connected_fn<ToCh, FrCh>)
233     -> connected_task<ToCh,FrCh> {
234     let from_child_port = comm::port::<FrCh>();
235     let from_child_chan = comm::chan(from_child_port);
236     let get_to_child_port = comm::port::<comm::chan<ToCh>>();
237     let get_to_child_chan = comm::chan(get_to_child_port);
238     let child_task = spawn(sendfn[move f]() {
239         let to_child_port = comm::port::<ToCh>();
240         comm::send(get_to_child_chan, comm::chan(to_child_port));
241         f(to_child_port, from_child_chan);
242     });
243     let to_child_chan = comm::recv(get_to_child_port);
244     ret {from_child: from_child_port,
245          to_child: to_child_chan,
246          task: child_task};
247 }
248
249 /* Section: Operations */
250
251 /*
252 Type: get_task
253
254 Retreives a handle to the currently executing task
255 */
256 fn get_task() -> task { rustrt::get_task_id() }
257
258 /*
259 Function: sleep
260
261 Hints the scheduler to yield this task for a specified ammount of time.
262
263 Parameters:
264
265 time_in_us - maximum number of microseconds to yield control for
266 */
267 fn sleep(time_in_us: uint) {
268     let task = rustrt::rust_get_task();
269     let killed = false;
270     // FIXME: uncomment this when extfmt is moved to core
271     // in a snapshot.
272     // #debug("yielding for %u us", time_in_us);
273     rusti::task_sleep(task, time_in_us, killed);
274     if killed {
275         fail "killed";
276     }
277 }
278
279 /*
280 Function: yield
281
282 Yield control to the task scheduler
283
284 The scheduler may schedule another task to execute.
285 */
286 fn yield() { sleep(1u) }
287
288 /*
289 Function: join
290
291 Wait for a child task to exit
292
293 The child task must have been spawned with <spawn_joinable>, which
294 produces a notification port that the child uses to communicate its
295 exit status.
296
297 Returns:
298
299 A task_result indicating whether the task terminated normally or failed
300 */
301 fn join(task_port: joinable_task) -> task_result {
302     let (id, port) = task_port;
303     alt comm::recv::<task_notification>(port) {
304       exit(_id, res) {
305         if _id == id {
306             ret res
307         } else {
308             // FIXME: uncomment this when extfmt is moved to core
309             // in a snapshot.
310             // fail #fmt["join received id %d, expected %d", _id, id]
311             fail;
312         }
313       }
314     }
315 }
316
317 /*
318 Function: unsupervise
319
320 Detaches this task from its parent in the task tree
321
322 An unsupervised task will not propagate its failure up the task tree
323 */
324 fn unsupervise() { ret sys::unsupervise(); }
325
326 /*
327 Function: pin
328
329 Pins the current task and future child tasks to a single scheduler thread
330 */
331 fn pin() { rustrt::pin_task(); }
332
333 /*
334 Function: unpin
335
336 Unpin the current task and future child tasks
337 */
338 fn unpin() { rustrt::unpin_task(); }
339
340 // Local Variables:
341 // mode: rust;
342 // fill-column: 78;
343 // indent-tabs-mode: nil
344 // c-basic-offset: 4
345 // buffer-file-coding-system: utf-8-unix
346 // End: