14.10 复用

    客户端(Client)可以是运行在任意设备上的任意程序,它会按需发送请求(request)至服务器。服务器(Server)接收到这个请求后开始相应的工作,然后再将响应(response)返回给客户端。典型情况下一般是多个客户端(即多个请求)对应一个(或少量)服务器。例如我们日常使用的浏览器客户端,其功能就是向服务器请求网页。而Web服务器则会向浏览器响应网页数据。

    使用Go的服务器通常会在协程中执行向客户端的响应,故而会对每一个客户端请求启动一个协程。一个常用的操作方法是客户端请求自身中包含一个通道,而服务器则向这个通道发送响应。

    例如下面这个结构,其中内嵌了一个replyc通道。

    或者更通俗的:

    1. type Reply struct{...}
    2. type Request struct{
    3. arg1, arg2, arg3 some_type
    4. replyc chan *Reply
    5. }

    接下来先使用简单的形式,服务器会为每一个请求启动一个协程并在其中执行run()函数,此举会将类型为binOpop操作返回的int值发送到replyc通道。

    1. type binOp func(a, b int) int
    2. func run(op binOp, req *Request) {
    3. req.replyc <- op(req.a, req.b)
    4. }

    server协程会无限循环以从chan *Request接收请求,并且为了避免被长时间操作所堵塞,它将为每一个请求启动一个协程来做具体的工作:

    1. func server(op binOp, service chan *Request) {
    2. for {
    3. req := <-service; // requests arrive here
    4. // start goroutine for request:
    5. go run(op, req); // don’t wait for op to complete
    6. }
    7. }

    startServer则会在main协程中被调用。

    在以下测试例子中,100个请求会被发送到服务器,只有它们全部被送达后我们才会按相反的顺序检查响应:

    1. func main() {
    2. adder := startServer(func(a, b int) int { return a + b })
    3. const N = 100
    4. var reqs [N]Request
    5. for i := 0; i < N; i++ {
    6. req := &reqs[i]
    7. req.a = i
    8. req.b = i + N
    9. req.replyc = make(chan int)
    10. adder <- req // adder is a channel of requests
    11. }
    12. // checks:
    13. for i := N - 1; i >= 0; i-- {
    14. // doesn’t matter what order
    15. if <-reqs[i].replyc != N+2*i {
    16. fmt.Println(“fail at”, i)
    17. } else {
    18. fmt.Println(“Request “, i, is ok!”)
    19. }
    20. }
    21. fmt.Println(“done”)
    22. }

    这些代码可以在找到

    输出:

    1. Request 99 is ok!
    2. Request 98 is ok!
    3. ...
    4. Request 1 is ok!
    5. Request 0 is ok!
    6. done

    这个程序仅启动了100个协程。然而即使执行100,000个协程我们也能在数秒内看到它完成。这说明了Go的协程是如何的轻量:如果我们启动相同数量的真实的线程,程序早就崩溃了。

    示例: 14.14-multiplex_server.go

    1. package main
    2. import "fmt"
    3. type Request struct {
    4. replyc chan int // reply channel inside the Request
    5. type binOp func(a, b int) int
    6. func run(op binOp, req *Request) {
    7. req.replyc <- op(req.a, req.b)
    8. }
    9. func server(op binOp, service chan *Request) {
    10. for {
    11. req := <-service // requests arrive here
    12. // start goroutine for request:
    13. go run(op, req) // don't wait for op
    14. }
    15. }
    16. func startServer(op binOp) chan *Request {
    17. reqChan := make(chan *Request)
    18. go server(op, reqChan)
    19. return reqChan
    20. }
    21. func main() {
    22. adder := startServer(func(a, b int) int { return a + b })
    23. const N = 100
    24. var reqs [N]Request
    25. for i := 0; i < N; i++ {
    26. req := &reqs[i]
    27. req.a = i
    28. req.b = i + N
    29. req.replyc = make(chan int)
    30. adder <- req
    31. }
    32. // checks:
    33. for i := N - 1; i >= 0; i-- { // doesn't matter what order
    34. if <-reqs[i].replyc != N+2*i {
    35. fmt.Println("fail at", i)
    36. } else {
    37. fmt.Println("Request ", i, " is ok!")
    38. }
    39. }
    40. fmt.Println("done")
    41. }

    server函数现在则使用selectservice通道和quit通道之间做出选择:

    1. func server(op binOp, service chan *request, quit chan bool) {
    2. for {
    3. select {
    4. case req := <-service:
    5. go run(op, req)
    6. case <-quit:
    7. return
    8. }
    9. }
    10. }

    当通道接收到一个true值时,server就会返回并结束。

    main函数中我们做出如下更改:

    1. adder, quit := startServer(func(a, b int) int { return a + b })

    main函数的结尾处我们放入这一行:quit <- true

    完整的代码在 multiplex_server2.go,输出和上一个版本是一样的。

    示例:

    1. package main
    2. type Request struct {
    3. a, b int
    4. replyc chan int // reply channel inside the Request
    5. }
    6. type binOp func(a, b int) int
    7. func run(op binOp, req *Request) {
    8. req.replyc <- op(req.a, req.b)
    9. }
    10. func server(op binOp, service chan *Request, quit chan bool) {
    11. for {
    12. select {
    13. case req := <-service:
    14. go run(op, req)
    15. case <-quit:
    16. return
    17. }
    18. }
    19. }
    20. func startServer(op binOp) (service chan *Request, quit chan bool) {
    21. service = make(chan *Request)
    22. quit = make(chan bool)
    23. go server(op, service, quit)
    24. return service, quit
    25. }
    26. func main() {
    27. adder, quit := startServer(func(a, b int) int { return a + b })
    28. const N = 100
    29. var reqs [N]Request
    30. for i := 0; i < N; i++ {
    31. req := &reqs[i]
    32. req.a = i
    33. req.b = i + N
    34. req.replyc = make(chan int)
    35. adder <- req
    36. }
    37. // checks:
    38. for i := N - 1; i >= 0; i-- { // doesn't matter what order
    39. if <-reqs[i].replyc != N+2*i {
    40. fmt.Println("fail at", i)
    41. } else {
    42. fmt.Println("Request ", i, " is ok!")
    43. }
    44. }
    45. quit <- true
    46. fmt.Println("done")
    47. }