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-15 18:54:07 -07:00
|
|
|
type request struct {
|
2008-09-16 12:00:11 -06:00
|
|
|
a, b int;
|
2009-01-06 16:49:27 -07:00
|
|
|
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-01-30 12:14:48 -07:00
|
|
|
reply := op(req.a, req.b);
|
|
|
|
req.replyc <- reply;
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
|
2009-01-30 15:39:31 -07:00
|
|
|
func server(op binOp, service chan *request, quit chan bool) {
|
2008-09-16 12:00:11 -06:00
|
|
|
for {
|
|
|
|
select {
|
2009-01-15 18:54:07 -07:00
|
|
|
case req := <-service:
|
|
|
|
go run(op, req); // don't wait for it
|
2008-09-16 12:00:11 -06:00
|
|
|
case <-quit:
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-01-30 15:39:31 -07:00
|
|
|
func startServer(op binOp) (service chan *request, quit chan bool) {
|
2009-01-15 18:54:07 -07:00
|
|
|
service = make(chan *request);
|
2009-01-06 16:49:27 -07:00
|
|
|
quit = make(chan bool);
|
2009-01-15 18:54:07 -07:00
|
|
|
go server(op, service, quit);
|
2008-09-16 12:00:11 -06:00
|
|
|
return service, quit;
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2009-01-15 18:54:07 -07:00
|
|
|
adder, quit := startServer(func(a, b int) int { return a + b });
|
2008-09-16 12:00:11 -06:00
|
|
|
const N = 100;
|
2009-01-15 18:54:07 -07:00
|
|
|
var reqs [N]request;
|
2008-09-16 12:00:11 -06:00
|
|
|
for i := 0; i < N; i++ {
|
|
|
|
req := &reqs[i];
|
|
|
|
req.a = i;
|
|
|
|
req.b = i + N;
|
2009-01-06 16:49:27 -07:00
|
|
|
req.replyc = make(chan int);
|
2008-09-16 20:40:38 -06:00
|
|
|
adder <- req;
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
for i := N-1; i >= 0; i-- { // doesn't matter what order
|
|
|
|
if <-reqs[i].replyc != N + 2*i {
|
2009-03-18 15:09:16 -06:00
|
|
|
fmt.Println("fail at", i);
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
}
|
2008-09-16 20:40:38 -06:00
|
|
|
quit <- true;
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|