You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go Tour并发示例中为何必须使用goroutine?

Why Goroutines Are Required Here (And Why Ditching Them Triggers Deadlock)

Let's break this down clearly—your confusion totally makes sense, because the deadlock here ties directly to how Go's unbuffered channels work.

First, the Core Rule: Unbuffered Channels Block Senders Until a Receiver Is Ready

Go's unbuffered channels (which is what you get when you call make(chan int) without a buffer size) have a strict rule:

  • A channel <- value operation will freeze the current goroutine until another goroutine executes <-channel to pick up that value.
  • Similarly, a receive operation blocks until a sender sends a value.

What Works With Goroutines (Original Code)

When you use go sum(...), you're spinning up two separate goroutines to handle the sum calculations. Here's the play-by-play:

  1. The main goroutine starts both sum goroutines, then immediately moves to x, y := <-c, <-c—it stops here, waiting to receive two values from the channel.
  2. Each sum goroutine runs independently, computes its slice's total, then sends the result to c. Since the main goroutine is already waiting to receive from c, these send operations don't get stuck—they drop the value into the channel and exit.
  3. Once main gets both values, it prints and exits cleanly.

What Breaks Without Goroutines

If you remove the go keywords, everything runs in the main goroutine alone. Let's walk through that:

  1. Main calls sum(s[:len(s)/2], c) directly. It runs through the sum calculation, then hits c <- sum.
  2. Now, main is stuck. There's no other goroutine running to receive from c—main itself hasn't even gotten to the line where it would do <-c. The send operation can't complete, so main just sits here forever.
  3. Go detects that all goroutines (only main, in this case) are blocked with no way to unblock, so it throws that fatal deadlock error.

The Short Version

Goroutines let us split the "sending" and "receiving" work into separate execution flows. Without them, your send operation has no receiver ready to catch the value, so it locks up the whole program. Unbuffered channels rely on having both a sender and receiver active at the same time—and goroutines make that concurrency possible.


内容的提问来源于stack exchange,提问作者Debo Akeredolu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:00:41