Search code examples
gorpc

Does rpc Call method run in the same go routine as the server?


My server:

func (t *Arith) Multiply(args *Args, reply *int) error {
    *reply = args.A * args.B
    return nil
}
func main() {
    arith := new(Arith)
    rpc.Register(arith)
    rpc.HandleHTTP()
    l, e := net.Listen("tcp", ":1234")
    if e != nil {
        log.Fatal("listen error:", e)
    }
    go http.Serve(l, nil)
}

Client:

client.Call("Arith.Multiply", args, &reply)

I think then Multiply run in another go routine? The client.Call() actually invokes go server.SomeFun()?


Solution

  • Each http request has its own goroutine, that's a property of the http.Server itself, and net/rpc builds on top of it.

    From the documentation of http.Serve:

    Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them. Handler is typically nil, in which case the DefaultServeMux is used.

    And from rpc.HandleHTTP:

    HandleHTTP registers an HTTP handler for RPC messages to DefaultServer on DefaultRPCPath and a debugging handler on DefaultDebugPath. It is still necessary to invoke http.Serve(), typically in a go statement.