douduo2407 2016-12-02 15:53
浏览 20
已采纳

为什么goroutines没有`.join`操作?

Why is there no .join operation (i.e., block until finished) operation on goroutines? Instead of having to use channels to communicate when to proceed in the main goroutine?

It feels like I'm missing something fundamental about the theory around CSP.

EDIT: I'm asking "why is it so", not "how do I accomplish this".

  • 写回答

1条回答 默认 最新

  • doujiang5211 2016-12-02 16:03
    关注

    This is simply because goroutines are not threads. A given goroutine can be scheduled by the Go runtime to be associated to an Operating System thread, but for example in the case of blocking I/O operations, said threads can be associated to other goroutines while the other one is waiting.

    What does this mean?

    Joining needs a synchronization object in order to know when a thread is finished. As Go's goroutines are actually just very lightweight objects that only possess a stack, they do not provide such synchronization objects directly.

    Go's CSP premise is that you can instanciate thousands of goroutines very cheaply, and only use as many threads as you have physical CPU cores. In the perspective of the OS, synchronization objects are expensive, therefore having such objects for each goroutine would be very inefficient.

    Instead, synchronization is attained by using channels or WaitGroup's from the sync package.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度