multiplex_server3.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import "fmt"
  6. type Request struct {
  7. a, b int
  8. replyc chan int // reply channel inside the Request
  9. }
  10. type binOp func(a, b int) int
  11. func run(op binOp, req *Request) {
  12. req.replyc <- op(req.a, req.b)
  13. }
  14. func (r *Request) String() string {
  15. return fmt.Sprintf("%d+%d=%d", r.a, r.b, <-r.replyc)
  16. }
  17. func server(op binOp, service chan *Request, quit chan bool) {
  18. for {
  19. select {
  20. case req := <-service:
  21. go run(op, req)
  22. case <-quit:
  23. return // stop infinite loop
  24. }
  25. }
  26. }
  27. func startServer(op binOp) (service chan *Request, quit chan bool) {
  28. service = make(chan *Request)
  29. quit = make(chan bool)
  30. go server(op, service, quit)
  31. return service, quit
  32. }
  33. func main() {
  34. adder, quit := startServer(func(a, b int) int { return a + b })
  35. // make requests:
  36. req1 := &Request{3, 4, make(chan int)}
  37. req2 := &Request{150, 250, make(chan int)}
  38. // send requests on the service channel
  39. adder <- req1
  40. adder <- req2
  41. // ask for the results: ( method String() is called )
  42. fmt.Println(req1, req2)
  43. // shutdown server:
  44. quit <- true
  45. fmt.Print("done")
  46. }
  47. /* output:
  48. 3+4=7 150+250=400
  49. done
  50. */