OLD | NEW |
1 // Copyright 2009 The Go Authors. All rights reserved. | 1 // Copyright 2009 The Go Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style | 2 // Use of this source code is governed by a BSD-style |
3 // license that can be found in the LICENSE file. | 3 // license that can be found in the LICENSE file. |
4 | 4 |
5 package main | 5 package main |
6 | 6 |
7 import "fmt" | 7 import "fmt" |
8 | 8 |
9 type request struct { | 9 type request struct { |
10 » a, b int; | 10 » a, b int |
11 » replyc chan int; | 11 » replyc chan int |
12 } | 12 } |
13 | 13 |
14 type binOp func(a, b int) int | 14 type binOp func(a, b int) int |
15 | 15 |
16 func run(op binOp, req *request) { | 16 func run(op binOp, req *request) { |
17 » reply := op(req.a, req.b); | 17 » reply := op(req.a, req.b) |
18 » req.replyc <- reply; | 18 » req.replyc <- reply |
19 } | 19 } |
20 | 20 |
21 func server(op binOp, service chan *request) { | 21 func server(op binOp, service chan *request) { |
22 for { | 22 for { |
23 » » req := <-service; | 23 » » req := <-service |
24 » » go run(op, req); // don't wait for it | 24 » » go run(op, req) // don't wait for it |
25 } | 25 } |
26 } | 26 } |
27 | 27 |
28 func startServer(op binOp) chan *request { | 28 func startServer(op binOp) chan *request { |
29 » req := make(chan *request); | 29 » req := make(chan *request) |
30 » go server(op, req); | 30 » go server(op, req) |
31 » return req; | 31 » return req |
32 } | 32 } |
33 | 33 |
34 func main() { | 34 func main() { |
35 » adder := startServer(func(a, b int) int { return a + b }); | 35 » adder := startServer(func(a, b int) int { return a + b }) |
36 » const N = 100; | 36 » const N = 100 |
37 » var reqs [N]request; | 37 » var reqs [N]request |
38 for i := 0; i < N; i++ { | 38 for i := 0; i < N; i++ { |
39 » » req := &reqs[i]; | 39 » » req := &reqs[i] |
40 » » req.a = i; | 40 » » req.a = i |
41 » » req.b = i + N; | 41 » » req.b = i + N |
42 » » req.replyc = make(chan int); | 42 » » req.replyc = make(chan int) |
43 » » adder <- req; | 43 » » adder <- req |
44 } | 44 } |
45 for i := N-1; i >= 0; i-- { // doesn't matter what order | 45 for i := N-1; i >= 0; i-- { // doesn't matter what order |
46 if <-reqs[i].replyc != N + 2*i { | 46 if <-reqs[i].replyc != N + 2*i { |
47 » » » fmt.Println("fail at", i); | 47 » » » fmt.Println("fail at", i) |
48 } | 48 } |
49 } | 49 } |
50 » fmt.Println("done"); | 50 » fmt.Println("done") |
51 } | 51 } |
OLD | NEW |