dsvd407787736 2018-10-25 19:26
浏览 86

如何使用context.Context在函数调用链中取消

Suppose I have these functions:

func A(ctx context.Context) {
    // A takes some time to process
}

func B(ctx context.Context) {
    // B takes some time to process
}

func C(ctx context.Context) {
    // C takes some time to process
}

Note: Every function call takes some time to process.

Note: B should be called inside function A & C should be called inside function B.

Just need an example for this specific situation.

  • 写回答

1条回答 默认 最新

  • dta38159 2018-10-25 20:14
    关注

    You just pass the same context as the argument, but whenever you wait for results from channelemote server\anything you use select statement with waiting for the <- ctx.Done(). Whenever the context would be canceled (by cancel function or due to the timeout), the internal chan would be closed and the receive operation always unblocks on the closed channel.

    The general post about cancelation (without context, but mentally replace doneCh with ctx.Done()) https://blog.golang.org/pipelines

    Talk about cancelation (the context example from page 15) https://talks.golang.org/2014/gotham-context.slide#15

    Couple of examples https://www.sohamkamani.com/blog/golang/2018-06-17-golang-using-context-cancellation/

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题