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, quit chan bool) { | 21 func server(op binOp, service chan *request, quit chan bool) { |
22 for { | 22 for { |
23 select { | 23 select { |
24 case req := <-service: | 24 case req := <-service: |
25 » » » go run(op, req); // don't wait for it | 25 » » » go run(op, req) // don't wait for it |
26 case <-quit: | 26 case <-quit: |
27 » » » return; | 27 » » » return |
28 } | 28 } |
29 } | 29 } |
30 } | 30 } |
31 | 31 |
32 func startServer(op binOp) (service chan *request, quit chan bool) { | 32 func startServer(op binOp) (service chan *request, quit chan bool) { |
33 » service = make(chan *request); | 33 » service = make(chan *request) |
34 » quit = make(chan bool); | 34 » quit = make(chan bool) |
35 » go server(op, service, quit); | 35 » go server(op, service, quit) |
36 » return service, quit; | 36 » return service, quit |
37 } | 37 } |
38 | 38 |
39 func main() { | 39 func main() { |
40 » adder, quit := startServer(func(a, b int) int { return a + b }); | 40 » adder, quit := startServer(func(a, b int) int { return a + b }) |
41 » const N = 100; | 41 » const N = 100 |
42 » var reqs [N]request; | 42 » var reqs [N]request |
43 for i := 0; i < N; i++ { | 43 for i := 0; i < N; i++ { |
44 » » req := &reqs[i]; | 44 » » req := &reqs[i] |
45 » » req.a = i; | 45 » » req.a = i |
46 » » req.b = i + N; | 46 » » req.b = i + N |
47 » » req.replyc = make(chan int); | 47 » » req.replyc = make(chan int) |
48 » » adder <- req; | 48 » » adder <- req |
49 } | 49 } |
50 for i := N-1; i >= 0; i-- { // doesn't matter what order | 50 for i := N-1; i >= 0; i-- { // doesn't matter what order |
51 if <-reqs[i].replyc != N + 2*i { | 51 if <-reqs[i].replyc != N + 2*i { |
52 » » » fmt.Println("fail at", i); | 52 » » » fmt.Println("fail at", i) |
53 } | 53 } |
54 } | 54 } |
55 » quit <- true; | 55 » quit <- true |
56 } | 56 } |
OLD | NEW |