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-01-20 20:32:36 -07:00
|
|
|
type request struct {
|
2009-01-09 16:16:31 -07: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-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) {
|
2008-09-16 12:00:11 -06:00
|
|
|
for {
|
2009-01-30 11:18:58 -07:00
|
|
|
req := <-service;
|
|
|
|
go run(op, req); // don't wait for it
|
2008-09-16 12:00:11 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-01-30 15:39:31 -07:00
|
|
|
func startServer(op binOp) chan *request {
|
2009-01-30 11:18:58 -07:00
|
|
|
req := make(chan *request);
|
|
|
|
go server(op, req);
|
2008-09-16 12:00:11 -06:00
|
|
|
return req;
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2009-01-20 20:32:36 -07:00
|
|
|
adder := startServer(func(a, b int) int { return a + b });
|
2008-09-16 12:00:11 -06:00
|
|
|
const N = 100;
|
2009-01-20 20:32:36 -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-09 16:13:26 -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 {
|
|
|
|
print("fail at ", i, "\n");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
print("done\n");
|
|
|
|
}
|