1
+ // Test for concurrent tasks
2
+
3
+ enum msg {
4
+ ready( comm:: chan < msg > ) ,
5
+ start,
6
+ done( int ) ,
7
+ }
8
+
9
+ fn calc ( children : uint , parent_ch : comm:: chan < msg > ) {
10
+ let port = comm:: port ( ) ;
11
+ let chan = comm:: chan ( port) ;
12
+ let child_chs = [ ] ;
13
+ let sum = 0 ;
14
+
15
+ iter:: repeat ( children) { ||
16
+ task:: spawn { ||
17
+ calc ( 0 u, chan) ;
18
+ } ;
19
+ }
20
+
21
+ iter:: repeat ( children) { ||
22
+ alt check comm:: recv ( port) {
23
+ ready ( child_ch) {
24
+ child_chs += [ child_ch] ;
25
+ }
26
+ }
27
+ }
28
+
29
+ comm:: send ( parent_ch, ready ( chan) ) ;
30
+
31
+ alt check comm:: recv ( port) {
32
+ start {
33
+ vec : : iter ( child_chs) { |child_ch|
34
+ comm:: send ( child_ch, start) ;
35
+ }
36
+ }
37
+ }
38
+
39
+ iter:: repeat ( children) { ||
40
+ alt check comm:: recv ( port) {
41
+ done ( child_sum) { sum += child_sum; }
42
+ }
43
+ }
44
+
45
+ comm:: send ( parent_ch, done ( sum + 1 ) ) ;
46
+ }
47
+
48
+ fn main ( args : [ str ] ) {
49
+ let children = if vec:: len ( args) == 2 u {
50
+ uint:: from_str ( args[ 1 ] )
51
+ } else {
52
+ 100 u
53
+ } ;
54
+ let port = comm:: port ( ) ;
55
+ let chan = comm:: chan ( port) ;
56
+ task:: spawn { ||
57
+ calc ( children, chan) ;
58
+ } ;
59
+ alt check comm:: recv ( port) {
60
+ ready ( chan) {
61
+ comm:: send ( chan, start) ;
62
+ }
63
+ }
64
+ let sum = alt check comm:: recv ( port) {
65
+ done ( sum) { sum }
66
+ } ;
67
+ #error ( "How many tasks? %d tasks." , sum) ;
68
+ }
0 commit comments