@@ -168,7 +168,6 @@ do spawn {
168
168
169
169
some_other_expensive_computation();
170
170
let result = port.recv();
171
-
172
171
# fn some_expensive_computation() -> int { 42 }
173
172
# fn some_other_expensive_computation() {}
174
173
~~~~
@@ -189,10 +188,10 @@ spawns the child task.
189
188
190
189
~~~~
191
190
# use task::{spawn};
192
- # use comm::{Port, Chan};
191
+ # use task::spawn;
192
+ # use pipes::{stream, Port, Chan};
193
193
# fn some_expensive_computation() -> int { 42 }
194
- # let port = Port();
195
- # let chan = port.chan();
194
+ # let (chan, port) = stream();
196
195
do spawn {
197
196
let result = some_expensive_computation();
198
197
chan.send(result);
@@ -221,10 +220,29 @@ let result = port.recv();
221
220
The ` Port ` and ` Chan ` pair created by ` stream ` enable efficient
222
221
communication between a single sender and a single receiver, but
223
222
multiple senders cannot use a single ` Chan ` , nor can multiple
224
- receivers use a single ` Port ` . What if our example needed to
225
- perform multiple computations across a number of tasks? In that
226
- case we might use a ` SharedChan ` , a type that allows a single
227
- ` Chan ` to be used by multiple senders.
223
+ receivers use a single ` Port ` . What if our example needed to perform
224
+ multiple computations across a number of tasks? The following cannot
225
+ be written:
226
+
227
+ ~~~ {.xfail-test}
228
+ # use task::{spawn};
229
+ # use pipes::{stream, Port, Chan};
230
+ # fn some_expensive_computation() -> int { 42 }
231
+ let (chan, port) = stream();
232
+
233
+ do spawn {
234
+ chan.send(some_expensive_computation());
235
+ }
236
+
237
+ // ERROR! The previous spawn statement already owns the channel,
238
+ // so the compiler will not allow it to be captured again
239
+ do spawn {
240
+ chan.send(some_expensive_computation());
241
+ }
242
+ ~~~
243
+
244
+ Instead we can use a ` SharedChan ` , a type that allows a single
245
+ ` Chan ` to be shared by multiple senders.
228
246
229
247
~~~
230
248
# use task::spawn;
@@ -263,13 +281,12 @@ might look like the example below.
263
281
# use task::spawn;
264
282
# use pipes::{stream, Port, Chan};
265
283
284
+ // Create a vector of ports, one for each child task
266
285
let ports = do vec::from_fn(3) |init_val| {
267
286
let (chan, port) = stream();
268
-
269
287
do spawn {
270
288
chan.send(some_expensive_computation(init_val));
271
289
}
272
-
273
290
port
274
291
};
275
292
0 commit comments