1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Task management.
*
* An executing Rust program consists of a tree of tasks, each with their own
* stack, and sole ownership of their allocated heap data. Tasks communicate
* with each other using ports and channels (see std::rt::comm for more info
* about how communication works).
*
* Tasks can be spawned in 3 different modes.
*
* * Bidirectionally linked: This is the default mode and it's what ```spawn``` does.
* Failures will be propagated from parent to child and vice versa.
*
* * Unidirectionally linked (parent->child): This type of task can be created with
* ```spawn_supervised```. In this case, failures are propagated from parent to child
* but not the other way around.
*
* * Unlinked: Tasks can be completely unlinked. These tasks can be created by using
* ```spawn_unlinked```. In this case failures are not propagated at all.
*
* Tasks' failure modes can be further configured. For instance, parent tasks can (un)watch
* children failures. Please, refer to TaskBuilder's documentation bellow for more information.
*
* When a (bi|uni)directionally linked task fails, its failure will be propagated to all tasks
* linked to it, this will cause such tasks to fail by a `linked failure`.
*
* Task Scheduling:
*
* By default, every task is created in the same scheduler as its parent, where it
* is scheduled cooperatively with all other tasks in that scheduler. Some specialized
* applications may want more control over their scheduling, in which case they can be
* spawned into a new scheduler with the specific properties required. See TaskBuilder's
* documentation bellow for more information.
*
* # Example
*
* ```
* do spawn {
* log(error, "Hello, World!");
* }
* ```
*/
#[allow(missing_doc)];
use prelude::*;
use cell::Cell;
use comm::{stream, Chan, GenericChan, GenericPort, Port, Peekable};
use result::{Result, Ok, Err};
use rt::in_green_task_context;
use rt::local::Local;
use rt::task::{UnwindResult, Success, Failure};
use send_str::{SendStr, IntoSendStr};
use unstable::finally::Finally;
use util;
#[cfg(test)] use any::Any;
#[cfg(test)] use cast;
#[cfg(test)] use comm::SharedChan;
#[cfg(test)] use comm;
#[cfg(test)] use ptr;
#[cfg(test)] use result;
#[cfg(test)] use task;
pub mod spawn;
/// Indicates the manner in which a task exited.
///
/// A task that completes without failing is considered to exit successfully.
/// Supervised ancestors and linked siblings may yet fail after this task
/// succeeds. Also note that in such a case, it may be nondeterministic whether
/// linked failure or successful exit happen first.
///
/// If you wish for this result's delivery to block until all linked and/or
/// children tasks complete, recommend using a result future.
pub type TaskResult = Result<(), ~Any>;
pub struct LinkedFailure;
pub struct TaskResultPort {
priv port: Port<UnwindResult>
}
fn to_task_result(res: UnwindResult) -> TaskResult {
match res {
Success => Ok(()), Failure(a) => Err(a),
}
}
impl GenericPort<TaskResult> for TaskResultPort {
#[inline]
fn recv(&self) -> TaskResult {
to_task_result(self.port.recv())
}
#[inline]
fn try_recv(&self) -> Option<TaskResult> {
self.port.try_recv().map(to_task_result)
}
}
impl Peekable<TaskResult> for TaskResultPort {
#[inline]
fn peek(&self) -> bool { self.port.peek() }
}
/// Scheduler modes
#[deriving(Eq)]
pub enum SchedMode {
/// Run task on the default scheduler
DefaultScheduler,
/// All tasks run in the same OS thread
SingleThreaded,
}
/**
* Scheduler configuration options
*
* # Fields
*
* * sched_mode - The operating mode of the scheduler
*
*/
pub struct SchedOpts {
priv mode: SchedMode,
}
/**
* Task configuration options
*
* # Fields
*
* * linked - Propagate failure bidirectionally between child and parent.
* True by default. If both this and 'supervised' are false, then
* either task's failure will not affect the other ("unlinked").
*
* * supervised - Propagate failure unidirectionally from parent to child,
* but not from child to parent. False by default.
*
* * watched - Make parent task collect exit status notifications from child
* before reporting its own exit status. (This delays the parent
* task's death and cleanup until after all transitively watched
* children also exit.) True by default.
*
* * indestructible - Configures the task to ignore kill signals received from
* linked failure. This may cause process hangs during
* failure if not used carefully, but causes task blocking
* code paths (e.g. port recv() calls) to be faster by 2
* atomic operations. False by default.
*
* * notify_chan - Enable lifecycle notifications on the given channel
*
* * name - A name for the task-to-be, for identification in failure messages.
*
* * sched - Specify the configuration of a new scheduler to create the task
* in. This is of particular importance for libraries which want to call
* into foreign code that blocks. Without doing so in a different
* scheduler other tasks will be impeded or even blocked indefinitely.
*/
pub struct TaskOpts {
priv linked: bool,
priv supervised: bool,
priv watched: bool,
priv indestructible: bool,
priv notify_chan: Option<Chan<UnwindResult>>,
name: Option<SendStr>,
sched: SchedOpts,
stack_size: Option<uint>
}
/**
* The task builder type.
*
* Provides detailed control over the properties and behavior of new tasks.
*/
// NB: Builders are designed to be single-use because they do stateful
// things that get weird when reusing - e.g. if you create a result future
// it only applies to a single task, so then you have to maintain Some
// potentially tricky state to ensure that everything behaves correctly
// when you try to reuse the builder to spawn a new task. We'll just
// sidestep that whole issue by making builders uncopyable and making
// the run function move them in.
// FIXME (#3724): Replace the 'consumed' bit with move mode on self
pub struct TaskBuilder {
opts: TaskOpts,
priv gen_body: Option<proc(v: proc()) -> proc()>,
priv can_not_copy: Option<util::NonCopyable>,
priv consumed: bool,
}
/**
* Generate the base configuration for spawning a task, off of which more
* configuration methods can be chained.
* For example, task().unlinked().spawn is equivalent to spawn_unlinked.
*/
pub fn task() -> TaskBuilder {
TaskBuilder {
opts: default_task_opts(),
gen_body: None,
can_not_copy: None,
consumed: false,
}
}
impl TaskBuilder {
fn consume(&mut self) -> TaskBuilder {
if self.consumed {
fail!("Cannot copy a task_builder"); // Fake move mode on self
}
self.consumed = true;
let gen_body = self.gen_body.take();
let notify_chan = self.opts.notify_chan.take();
let name = self.opts.name.take();
TaskBuilder {
opts: TaskOpts {
linked: self.opts.linked,
supervised: self.opts.supervised,
watched: self.opts.watched,
indestructible: self.opts.indestructible,
notify_chan: notify_chan,
name: name,
sched: self.opts.sched,
stack_size: self.opts.stack_size
},
gen_body: gen_body,
can_not_copy: None,
consumed: false
}
}
/// Decouple the child task's failure from the parent's. If either fails,
/// the other will not be killed.
pub fn unlinked(&mut self) {
self.opts.linked = false;
self.opts.watched = false;
}
/// Unidirectionally link the child task's failure with the parent's. The
/// child's failure will not kill the parent, but the parent's will kill
/// the child.
pub fn supervised(&mut self) {
self.opts.supervised = true;
self.opts.linked = false;
self.opts.watched = false;
}
/// Link the child task's and parent task's failures. If either fails, the
/// other will be killed.
pub fn linked(&mut self) {
self.opts.linked = true;
self.opts.supervised = false;
self.opts.watched = true;
}
/// Cause the parent task to collect the child's exit status (and that of
/// all transitively-watched grandchildren) before reporting its own.
pub fn watched(&mut self) {
self.opts.watched = true;
}
/// Allow the child task to outlive the parent task, at the possible cost
/// of the parent reporting success even if the child task fails later.
pub fn unwatched(&mut self) {
self.opts.watched = false;
}
/// Cause the child task to ignore any kill signals received from linked
/// failure. This optimizes context switching, at the possible expense of
/// process hangs in the case of unexpected failure.
pub fn indestructible(&mut self) {
self.opts.indestructible = true;
}
/// Get a future representing the exit status of the task.
///
/// Taking the value of the future will block until the child task
/// terminates. The future result return value will be created *before* the task is
/// spawned; as such, do not invoke .get() on it directly;
/// rather, store it in an outer variable/list for later use.
///
/// Note that the future returned by this function is only useful for
/// obtaining the value of the next task to be spawning with the
/// builder. If additional tasks are spawned with the same builder
/// then a new result future must be obtained prior to spawning each
/// task.
///
/// # Failure
/// Fails if a future_result was already set for this task.
pub fn future_result(&mut self) -> TaskResultPort {
// FIXME (#3725): Once linked failure and notification are
// handled in the library, I can imagine implementing this by just
// registering an arbitrary number of task::on_exit handlers and
// sending out messages.
if self.opts.notify_chan.is_some() {
fail!("Can't set multiple future_results for one task!");
}
// Construct the future and give it to the caller.
let (notify_pipe_po, notify_pipe_ch) = stream::<UnwindResult>();
// Reconfigure self to use a notify channel.
self.opts.notify_chan = Some(notify_pipe_ch);
TaskResultPort { port: notify_pipe_po }
}
/// Name the task-to-be. Currently the name is used for identification
/// only in failure messages.
pub fn name<S: IntoSendStr>(&mut self, name: S) {
self.opts.name = Some(name.into_send_str());
}
/// Configure a custom scheduler mode for the task.
pub fn sched_mode(&mut self, mode: SchedMode) {
self.opts.sched.mode = mode;
}
/**
* Add a wrapper to the body of the spawned task.
*
* Before the task is spawned it is passed through a 'body generator'
* function that may perform local setup operations as well as wrap
* the task body in remote setup operations. With this the behavior
* of tasks can be extended in simple ways.
*
* This function augments the current body generator with a new body
* generator by applying the task body which results from the
* existing body generator to the new body generator.
*/
pub fn add_wrapper(&mut self, wrapper: proc(v: proc()) -> proc()) {
let prev_gen_body = self.gen_body.take();
let prev_gen_body = match prev_gen_body {
Some(gen) => gen,
None => {
let f: proc(proc()) -> proc() = |body| body;
f
}
};
let prev_gen_body = Cell::new(prev_gen_body);
let next_gen_body = {
let f: proc(proc()) -> proc() = |body| {
let prev_gen_body = prev_gen_body.take();
wrapper(prev_gen_body(body))
};
f
};
self.gen_body = Some(next_gen_body);
}
/**
* Creates and executes a new child task
*
* Sets up a new task with its own call stack and schedules it to run
* the provided unique closure. The task has the properties and behavior
* specified by the task_builder.
*
* # Failure
*
* When spawning into a new scheduler, the number of threads requested
* must be greater than zero.
*/
pub fn spawn(&mut self, f: proc()) {
let gen_body = self.gen_body.take();
let notify_chan = self.opts.notify_chan.take();
let name = self.opts.name.take();
let x = self.consume();
let opts = TaskOpts {
linked: x.opts.linked,
supervised: x.opts.supervised,
watched: x.opts.watched,
indestructible: x.opts.indestructible,
notify_chan: notify_chan,
name: name,
sched: x.opts.sched,
stack_size: x.opts.stack_size
};
let f = match gen_body {
Some(gen) => {
gen(f)
}
None => {
f
}
};
spawn::spawn_raw(opts, f);
}
/// Runs a task, while transferring ownership of one argument to the child.
pub fn spawn_with<A:Send>(&mut self, arg: A, f: proc(v: A)) {
let arg = Cell::new(arg);
do self.spawn {
f(arg.take());
}
}
/**
* Execute a function in another task and return either the return value
* of the function or result::err.
*
* # Return value
*
* If the function executed successfully then try returns result::ok
* containing the value returned by the function. If the function fails
* then try returns result::err containing nil.
*
* # Failure
* Fails if a future_result was already set for this task.
*/
pub fn try<T:Send>(&mut self, f: proc() -> T) -> Result<T, ~Any> {
let (po, ch) = stream::<T>();
let result = self.future_result();
do self.spawn {
ch.send(f());
}
match result.recv() {
Ok(()) => Ok(po.recv()),
Err(cause) => Err(cause)
}
}
}
/* Task construction */
pub fn default_task_opts() -> TaskOpts {
/*!
* The default task options
*
* By default all tasks are supervised by their parent, are spawned
* into the same scheduler, and do not post lifecycle notifications.
*/
TaskOpts {
linked: true,
supervised: false,
watched: true,
indestructible: false,
notify_chan: None,
name: None,
sched: SchedOpts {
mode: DefaultScheduler,
},
stack_size: None
}
}
/* Spawn convenience functions */
/// Creates and executes a new child task
///
/// Sets up a new task with its own call stack and schedules it to run
/// the provided unique closure.
///
/// This function is equivalent to `task().spawn(f)`.
pub fn spawn(f: proc()) {
let mut task = task();
task.spawn(f)
}
/// Creates a child task unlinked from the current one. If either this
/// task or the child task fails, the other will not be killed.
pub fn spawn_unlinked(f: proc()) {
let mut task = task();
task.unlinked();
task.spawn(f)
}
pub fn spawn_supervised(f: proc()) {
/*!
* Creates a child task supervised by the current one. If the child
* task fails, the parent will not be killed, but if the parent fails,
* the child will be killed.
*/
let mut task = task();
task.supervised();
task.spawn(f)
}
/// Creates a child task that cannot be killed by linked failure. This causes
/// its context-switch path to be faster by 2 atomic swap operations.
/// (Note that this convenience wrapper still uses linked-failure, so the
/// child's children will still be killable by the parent. For the fastest
/// possible spawn mode, use task::task().unlinked().indestructible().spawn.)
pub fn spawn_indestructible(f: proc()) {
let mut task = task();
task.indestructible();
task.spawn(f)
}
pub fn spawn_with<A:Send>(arg: A, f: proc(v: A)) {
/*!
* Runs a task, while transferring ownership of one argument to the
* child.
*
* This is useful for transferring ownership of noncopyables to
* another task.
*
* This function is equivalent to `task().spawn_with(arg, f)`.
*/
let mut task = task();
task.spawn_with(arg, f)
}
pub fn spawn_sched(mode: SchedMode, f: proc()) {
/*!
* Creates a new task on a new or existing scheduler.
*
* When there are no more tasks to execute the
* scheduler terminates.
*
* # Failure
*
* In manual threads mode the number of threads requested must be
* greater than zero.
*/
let mut task = task();
task.sched_mode(mode);
task.spawn(f)
}
pub fn try<T:Send>(f: proc() -> T) -> Result<T, ~Any> {
/*!
* Execute a function in another task and return either the return value
* of the function or result::err.
*
* This is equivalent to task().supervised().try.
*/
let mut task = task();
task.supervised();
task.try(f)
}
/* Lifecycle functions */
/// Read the name of the current task.
pub fn with_task_name<U>(blk: |Option<&str>| -> U) -> U {
use rt::task::Task;
if in_green_task_context() {
do Local::borrow |task: &mut Task| {
match task.name {
Some(ref name) => blk(Some(name.as_slice())),
None => blk(None)
}
}
} else {
fail!("no task name exists in non-green task context")
}
}
pub fn deschedule() {
//! Yield control to the task scheduler
use rt::local::Local;
use rt::sched::Scheduler;
// FIXME(#7544): Optimize this, since we know we won't block.
let sched: ~Scheduler = Local::take();
sched.yield_now();
}
pub fn failing() -> bool {
//! True if the running task has failed
use rt::task::Task;
do Local::borrow |local: &mut Task| {
local.unwinder.unwinding
}
}
/**
* Temporarily make the task unkillable
*
* # Example
*
* ```
* do task::unkillable {
* // detach / deschedule / destroy must all be called together
* rustrt::rust_port_detach(po);
* // This must not result in the current task being killed
* task::deschedule();
* rustrt::rust_port_destroy(po);
* }
* ```
*/
pub fn unkillable<U>(f: || -> U) -> U {
use rt::task::Task;
unsafe {
if in_green_task_context() {
// The inhibits/allows might fail and need to borrow the task.
let t: *mut Task = Local::unsafe_borrow();
do (|| {
(*t).death.inhibit_kill((*t).unwinder.unwinding);
f()
}).finally {
(*t).death.allow_kill((*t).unwinder.unwinding);
}
} else {
// FIXME(#3095): This should be an rtabort as soon as the scheduler
// no longer uses a workqueue implemented with an Exclusive.
f()
}
}
}
/**
* Makes killable a task marked as unkillable. This
* is meant to be used only nested in unkillable.
*
* # Example
*
* ```
* do task::unkillable {
* do task::rekillable {
* // Task is killable
* }
* // Task is unkillable again
* }
*/
pub fn rekillable<U>(f: || -> U) -> U {
use rt::task::Task;
unsafe {
if in_green_task_context() {
let t: *mut Task = Local::unsafe_borrow();
do (|| {
(*t).death.allow_kill((*t).unwinder.unwinding);
f()
}).finally {
(*t).death.inhibit_kill((*t).unwinder.unwinding);
}
} else {
// FIXME(#3095): As in unkillable().
f()
}
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_kill_unkillable_task() {
use rt::test::*;
// Attempt to test that when a kill signal is received at the start of an
// unkillable section, 'unkillable' unwinds correctly. This is actually
// quite a difficult race to expose, as the kill has to happen on a second
// CPU, *after* the spawner is already switched-back-to (and passes the
// killed check at the start of its timeslice). As far as I know, it's not
// possible to make this race deterministic, or even more likely to happen.
do run_in_uv_task {
do task::try {
do task::spawn {
fail!();
}
do task::unkillable { }
};
}
}
#[test]
#[ignore(cfg(windows))]
fn test_kill_rekillable_task() {
use rt::test::*;
// Tests that when a kill signal is received, 'rekillable' and
// 'unkillable' unwind correctly in conjunction with each other.
do run_in_uv_task {
do task::try {
do task::unkillable {
do task::rekillable {
do task::spawn {
fail!();
}
}
}
};
}
}
#[test]
#[should_fail]
#[ignore(cfg(windows))]
fn test_rekillable_not_nested() {
do rekillable {
// This should fail before
// receiving anything since
// this block should be nested
// into a unkillable block.
deschedule();
}
}
#[test]
#[ignore(cfg(windows))]
fn test_rekillable_nested_failure() {
let result = do task::try {
do unkillable {
do rekillable {
let (port,chan) = comm::stream();
do task::spawn { chan.send(()); fail!(); }
port.recv(); // wait for child to exist
port.recv(); // block forever, expect to get killed.
}
}
};
assert!(result.is_err());
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_cant_dup_task_builder() {
let mut builder = task();
builder.unlinked();
do builder.spawn {}
// FIXME(#3724): For now, this is a -runtime- failure, because we haven't
// got move mode on self. When 3724 is fixed, this test should fail to
// compile instead, and should go in tests/compile-fail.
do builder.spawn {} // b should have been consumed by the previous call
}
// The following 8 tests test the following 2^3 combinations:
// {un,}linked {un,}supervised failure propagation {up,down}wards.
// !!! These tests are dangerous. If Something is buggy, they will hang, !!!
// !!! instead of exiting cleanly. This might wedge the buildbots. !!!
#[cfg(test)]
fn block_forever() { let (po, _ch) = stream::<()>(); po.recv(); }
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_unlinked_unsup_no_fail_down() { // grandchild sends on a port
use rt::test::run_in_uv_task;
do run_in_uv_task {
let (po, ch) = stream();
let ch = SharedChan::new(ch);
do spawn_unlinked {
let ch = ch.clone();
do spawn_unlinked {
// Give middle task a chance to fail-but-not-kill-us.
do 16.times { task::deschedule(); }
ch.send(()); // If killed first, grandparent hangs.
}
fail!(); // Shouldn't kill either (grand)parent or (grand)child.
}
po.recv();
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_unlinked_unsup_no_fail_up() { // child unlinked fails
use rt::test::run_in_uv_task;
do run_in_uv_task {
do spawn_unlinked { fail!(); }
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_unlinked_sup_no_fail_up() { // child unlinked fails
use rt::test::run_in_uv_task;
do run_in_uv_task {
do spawn_supervised { fail!(); }
// Give child a chance to fail-but-not-kill-us.
do 16.times { task::deschedule(); }
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_unlinked_sup_fail_down() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
do spawn_supervised { block_forever(); }
fail!(); // Shouldn't leave a child hanging around.
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_linked_sup_fail_up() { // child fails; parent fails
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// Unidirectional "parenting" shouldn't override bidirectional linked.
// We have to cheat with opts - the interface doesn't support them because
// they don't make sense (redundant with task().supervised()).
let mut b0 = task();
b0.opts.linked = true;
b0.opts.supervised = true;
do b0.spawn {
fail!();
}
block_forever(); // We should get punted awake
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_linked_sup_fail_down() { // parent fails; child fails
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// We have to cheat with opts - the interface doesn't support them because
// they don't make sense (redundant with task().supervised()).
let mut b0 = task();
b0.opts.linked = true;
b0.opts.supervised = true;
do b0.spawn { block_forever(); }
fail!(); // *both* mechanisms would be wrong if this didn't kill the child
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_linked_unsup_fail_up() { // child fails; parent fails
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// Default options are to spawn linked & unsupervised.
do spawn { fail!(); }
block_forever(); // We should get punted awake
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_linked_unsup_fail_down() { // parent fails; child fails
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// Default options are to spawn linked & unsupervised.
do spawn { block_forever(); }
fail!();
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_linked_unsup_default_opts() { // parent fails; child fails
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// Make sure the above test is the same as this one.
let mut builder = task();
builder.linked();
do builder.spawn { block_forever(); }
fail!();
};
assert!(result.is_err());
}
}
// A couple bonus linked failure tests - testing for failure propagation even
// when the middle task exits successfully early before kill signals are sent.
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_failure_propagate_grandchild() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// Middle task exits; does grandparent's failure propagate across the gap?
do spawn_supervised {
do spawn_supervised { block_forever(); }
}
do 16.times { task::deschedule(); }
fail!();
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_failure_propagate_secondborn() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// First-born child exits; does parent's failure propagate to sibling?
do spawn_supervised {
do spawn { block_forever(); } // linked
}
do 16.times { task::deschedule(); }
fail!();
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_failure_propagate_nephew_or_niece() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// Our sibling exits; does our failure propagate to sibling's child?
do spawn { // linked
do spawn_supervised { block_forever(); }
}
do 16.times { task::deschedule(); }
fail!();
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_linked_sup_propagate_sibling() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result: Result<(), ~Any> = do try {
// Middle sibling exits - does eldest's failure propagate to youngest?
do spawn { // linked
do spawn { block_forever(); } // linked
}
do 16.times { task::deschedule(); }
fail!();
};
assert!(result.is_err());
}
}
#[test]
fn test_unnamed_task() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
do spawn {
do with_task_name |name| {
assert!(name.is_none());
}
}
}
}
#[test]
fn test_owned_named_task() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let mut t = task();
t.name(~"ada lovelace");
do t.spawn {
do with_task_name |name| {
assert!(name.unwrap() == "ada lovelace");
}
}
}
}
#[test]
fn test_static_named_task() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let mut t = task();
t.name("ada lovelace");
do t.spawn {
do with_task_name |name| {
assert!(name.unwrap() == "ada lovelace");
}
}
}
}
#[test]
fn test_send_named_task() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let mut t = task();
t.name("ada lovelace".into_send_str());
do t.spawn {
do with_task_name |name| {
assert!(name.unwrap() == "ada lovelace");
}
}
}
}
#[test]
fn test_run_basic() {
let (po, ch) = stream::<()>();
let mut builder = task();
do builder.spawn {
ch.send(());
}
po.recv();
}
#[cfg(test)]
struct Wrapper {
f: Option<Chan<()>>
}
#[test]
fn test_add_wrapper() {
let (po, ch) = stream::<()>();
let mut b0 = task();
let ch = Cell::new(ch);
do b0.add_wrapper |body| {
let ch = Cell::new(ch.take());
let result: proc() = || {
let ch = ch.take();
body();
ch.send(());
};
result
};
do b0.spawn { }
po.recv();
}
#[test]
fn test_future_result() {
let mut builder = task();
let result = builder.future_result();
do builder.spawn {}
assert!(result.recv().is_ok());
let mut builder = task();
let result = builder.future_result();
builder.unlinked();
do builder.spawn {
fail!();
}
assert!(result.recv().is_err());
}
#[test] #[should_fail]
fn test_back_to_the_future_result() {
let mut builder = task();
builder.future_result();
builder.future_result();
}
#[test]
fn test_try_success() {
match do try {
~"Success!"
} {
result::Ok(~"Success!") => (),
_ => fail!()
}
}
#[test]
fn test_try_fail() {
match do try {
fail!()
} {
result::Err(_) => (),
result::Ok(()) => fail!()
}
}
#[cfg(test)]
fn get_sched_id() -> int {
do Local::borrow |sched: &mut ::rt::sched::Scheduler| {
sched.sched_id() as int
}
}
#[test]
fn test_spawn_sched() {
let (po, ch) = stream::<()>();
let ch = SharedChan::new(ch);
fn f(i: int, ch: SharedChan<()>) {
let parent_sched_id = get_sched_id();
do spawn_sched(SingleThreaded) {
let child_sched_id = get_sched_id();
assert!(parent_sched_id != child_sched_id);
if (i == 0) {
ch.send(());
} else {
f(i - 1, ch.clone());
}
};
}
f(10, ch);
po.recv();
}
#[test]
fn test_spawn_sched_childs_on_default_sched() {
let (po, ch) = stream();
// Assuming tests run on the default scheduler
let default_id = get_sched_id();
let ch = Cell::new(ch);
do spawn_sched(SingleThreaded) {
let parent_sched_id = get_sched_id();
let ch = Cell::new(ch.take());
do spawn {
let ch = ch.take();
let child_sched_id = get_sched_id();
assert!(parent_sched_id != child_sched_id);
assert_eq!(child_sched_id, default_id);
ch.send(());
};
};
po.recv();
}
#[test]
fn test_spawn_sched_blocking() {
use unstable::mutex::Mutex;
unsafe {
// Testing that a task in one scheduler can block in foreign code
// without affecting other schedulers
do 20u.times {
let (start_po, start_ch) = stream();
let (fin_po, fin_ch) = stream();
let mut lock = Mutex::new();
let lock2 = Cell::new(lock.clone());
do spawn_sched(SingleThreaded) {
let mut lock = lock2.take();
lock.lock();
start_ch.send(());
// Block the scheduler thread
lock.wait();
lock.unlock();
fin_ch.send(());
};
// Wait until the other task has its lock
start_po.recv();
fn pingpong(po: &Port<int>, ch: &Chan<int>) {
let mut val = 20;
while val > 0 {
val = po.recv();
ch.send(val - 1);
}
}
let (setup_po, setup_ch) = stream();
let (parent_po, parent_ch) = stream();
do spawn {
let (child_po, child_ch) = stream();
setup_ch.send(child_ch);
pingpong(&child_po, &parent_ch);
};
let child_ch = setup_po.recv();
child_ch.send(20);
pingpong(&parent_po, &child_ch);
lock.lock();
lock.signal();
lock.unlock();
fin_po.recv();
lock.destroy();
}
}
}
#[cfg(test)]
fn avoid_copying_the_body(spawnfn: |v: proc()|) {
let (p, ch) = stream::<uint>();
let x = ~1;
let x_in_parent = ptr::to_unsafe_ptr(&*x) as uint;
do spawnfn || {
let x_in_child = ptr::to_unsafe_ptr(&*x) as uint;
ch.send(x_in_child);
}
let x_in_child = p.recv();
assert_eq!(x_in_parent, x_in_child);
}
#[test]
fn test_avoid_copying_the_body_spawn() {
avoid_copying_the_body(spawn);
}
#[test]
fn test_avoid_copying_the_body_task_spawn() {
do avoid_copying_the_body |f| {
let mut builder = task();
do builder.spawn || {
f();
}
}
}
#[test]
fn test_avoid_copying_the_body_try() {
do avoid_copying_the_body |f| {
do try || {
f()
};
}
}
#[test]
fn test_avoid_copying_the_body_unlinked() {
do avoid_copying_the_body |f| {
do spawn_unlinked || {
f();
}
}
}
#[ignore(reason = "linked failure")]
#[test]
#[should_fail]
fn test_unkillable() {
let (po, ch) = stream();
// We want to do this after failing
do spawn_unlinked {
do 10.times { deschedule() }
ch.send(());
}
do spawn {
deschedule();
// We want to fail after the unkillable task
// blocks on recv
fail!();
}
unsafe {
do unkillable {
let p = ~0;
let pp: *uint = cast::transmute(p);
// If we are killed here then the box will leak
po.recv();
let _p: ~int = cast::transmute(pp);
}
}
// Now we can be killed
po.recv();
}
#[ignore(reason = "linked failure")]
#[test]
#[should_fail]
fn test_unkillable_nested() {
let (po, ch) = comm::stream();
// We want to do this after failing
do spawn_unlinked || {
do 10.times { deschedule() }
ch.send(());
}
do spawn {
deschedule();
// We want to fail after the unkillable task
// blocks on recv
fail!();
}
unsafe {
do unkillable {
do unkillable {} // Here's the difference from the previous test.
let p = ~0;
let pp: *uint = cast::transmute(p);
// If we are killed here then the box will leak
po.recv();
let _p: ~int = cast::transmute(pp);
}
}
// Now we can be killed
po.recv();
}
#[test]
fn test_child_doesnt_ref_parent() {
// If the child refcounts the parent task, this will stack overflow when
// climbing the task tree to dereference each ancestor. (See #1789)
// (well, it would if the constant were 8000+ - I lowered it to be more
// valgrind-friendly. try this at home, instead..!)
static generations: uint = 16;
fn child_no(x: uint) -> proc() {
return || {
if x < generations {
let mut t = task();
t.unwatched();
t.spawn(child_no(x+1));
}
}
}
let mut t = task();
t.unwatched();
t.spawn(child_no(0));
}
#[test]
fn test_simple_newsched_spawn() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
spawn(||())
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_spawn_watched() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result = do try {
let mut t = task();
t.unlinked();
t.watched();
do t.spawn {
let mut t = task();
t.unlinked();
t.watched();
do t.spawn {
task::deschedule();
fail!();
}
}
};
assert!(result.is_err());
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_indestructible() {
use rt::test::run_in_uv_task;
do run_in_uv_task {
let result = do try {
let mut t = task();
t.watched();
t.supervised();
t.indestructible();
do t.spawn {
let (p1, _c1) = stream::<()>();
let (p2, c2) = stream::<()>();
let (p3, c3) = stream::<()>();
let mut t = task();
t.unwatched();
do t.spawn {
do (|| {
p1.recv(); // would deadlock if not killed
}).finally {
c2.send(());
};
}
let mut t = task();
t.unwatched();
do t.spawn {
p3.recv();
task::deschedule();
fail!();
}
c3.send(());
p2.recv();
}
};
assert!(result.is_ok());
}
}
#[test]
fn test_try_fail_message_static_str() {
match do try {
fail!("static string");
} {
Err(e) => {
type T = &'static str;
assert!(e.is::<T>());
assert_eq!(*e.move::<T>().unwrap(), "static string");
}
Ok(()) => fail!()
}
}
#[test]
fn test_try_fail_message_owned_str() {
match do try {
fail!(~"owned string");
} {
Err(e) => {
type T = ~str;
assert!(e.is::<T>());
assert_eq!(*e.move::<T>().unwrap(), ~"owned string");
}
Ok(()) => fail!()
}
}
#[test]
fn test_try_fail_message_any() {
match do try {
fail!(~413u16 as ~Any);
} {
Err(e) => {
type T = ~Any;
assert!(e.is::<T>());
let any = e.move::<T>().unwrap();
assert!(any.is::<u16>());
assert_eq!(*any.move::<u16>().unwrap(), 413u16);
}
Ok(()) => fail!()
}
}
#[ignore(reason = "linked failure")]
#[test]
fn test_try_fail_message_linked() {
match do try {
do spawn {
fail!()
}
} {
Err(ref e) if e.is::<LinkedFailure>() => {}
Err(_) | Ok(()) => fail!()
}
}
#[test]
fn test_try_fail_message_unit_struct() {
struct Juju;
match do try {
fail!(Juju)
} {
Err(ref e) if e.is::<Juju>() => {}
Err(_) | Ok(()) => fail!()
}
}
|