2008-09-16 12:00:11 -06:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
import "fmt"
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
type request struct {
|
2011-07-09 04:16:45 -06:00
|
|
|
a, b int
|
|
|
|
replyc chan int
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
|
2009-01-30 16:10:22 -07:00
|
|
|
type binOp func(a, b int) int
|
2008-09-16 14:14:44 -06:00
|
|
|
|
2009-01-30 15:39:31 -07:00
|
|
|
func run(op binOp, req *request) {
|
2009-12-15 16:29:53 -07:00
|
|
|
reply := op(req.a, req.b)
|
|
|
|
req.replyc <- reply
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
|
2011-11-10 15:02:14 -07:00
|
|
|
func server(op binOp, service <-chan *request) {
|
2008-09-16 12:00:11 -06:00
|
|
|
for {
|
2009-12-15 16:29:53 -07:00
|
|
|
req := <-service
|
2011-07-09 04:16:45 -06:00
|
|
|
go run(op, req) // don't wait for it
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-11-10 15:02:14 -07:00
|
|
|
func startServer(op binOp) chan<- *request {
|
2009-12-15 16:29:53 -07:00
|
|
|
req := make(chan *request)
|
|
|
|
go server(op, req)
|
|
|
|
return req
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2009-12-15 16:29:53 -07:00
|
|
|
adder := startServer(func(a, b int) int { return a + b })
|
|
|
|
const N = 100
|
|
|
|
var reqs [N]request
|
2008-09-16 12:00:11 -06:00
|
|
|
for i := 0; i < N; i++ {
|
2009-12-15 16:29:53 -07:00
|
|
|
req := &reqs[i]
|
|
|
|
req.a = i
|
|
|
|
req.b = i + N
|
|
|
|
req.replyc = make(chan int)
|
|
|
|
adder <- req
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
2011-07-09 04:16:45 -06:00
|
|
|
for i := N - 1; i >= 0; i-- { // doesn't matter what order
|
|
|
|
if <-reqs[i].replyc != N+2*i {
|
2009-12-15 16:29:53 -07:00
|
|
|
fmt.Println("fail at", i)
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
}
|
2009-12-15 16:29:53 -07:00
|
|
|
fmt.Println("done")
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|