Go Tour并发示例中为何必须使用goroutine?
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 <- valueoperation will freeze the current goroutine until another goroutine executes<-channelto 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:
- 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. - 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 fromc, these send operations don't get stuck—they drop the value into the channel and exit. - 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:
- Main calls
sum(s[:len(s)/2], c)directly. It runs through the sum calculation, then hitsc <- sum. - 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. - 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

