dprntkxh703029 2018-12-06 08:20
浏览 147
已采纳

net / rpc .Call和.Go有什么区别?

I’m just getting started with Golang and the net/rpc package. I’m trying to understand when you might use the asynchronous client.Go() call over the client.Call() method most examples online use. Would calling client.Call asynchronously via something like

go client.Call(...)

essentially be the same as using the client.Go call? I’ve seen this example online too (for example when calling multiple simultaneous RPCs).

  • 写回答

1条回答 默认 最新

  • doudou8893 2018-12-06 08:28
    关注

    As documented:

    Go invokes the function asynchronously. It returns the Call structure representing the invocation. The done channel will signal when the call is complete by returning the same Call object. If done is nil, Go will allocate a new channel. If non-nil, done must be buffered or Go will deliberately crash.

    What this means is that it issues the command, but does not wait for it to finish.

    By contrast:

    Call invokes the named function, waits for it to complete, and returns its error status.

    Neither method executes in a goroutine directly*--this is left as an exercise for the caller (so an argument might be made that Go is a misnomer).

    If you look at the source to Call, perhaps it is more clear:

    func (client *Client) Call(serviceMethod string, args interface{}, reply 
    interface{}) error {
        call := <-client.Go(serviceMethod, args, reply, make(chan *Call, 1)).Done
        return call.Error
    }
    

    So in actuality, Call is a wrapper around Go, which waits for the operation to complete, whereas Go is the underlying function, which leaves waiting up to the caller.

    *Clearly, in the background, a goroutine is involved somewhere, since this is a non-blocking operation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)