Goroutine Leaks From Unread Channels

A send to an unread unbuffered channel parks its goroutine forever — count them with runtime.NumGoroutine and cap the channel to let senders finish.

GoResilience

Code

gosnippet
47 lines
package main

import (
	"fmt"
	"runtime"
	"sync"
)

// sendAllLeaky:每个 goroutine 把结果发进无人接收的无缓冲通道
func sendAllLeaky(jobs []int, started *sync.WaitGroup) {
	ch := make(chan int) // 无缓冲,也没有接收方
	for _, job := range jobs {
		started.Add(1)
		go func() {
			started.Done() // 到达发送点
			ch <- job      // 无人接收:goroutine 永久停在这里
		}()
	}
}

// sendAllFixed:缓冲容量与任务数一致,发送方永不等待
func sendAllFixed(jobs []int) {
	var wg sync.WaitGroup
	ch := make(chan int, len(jobs))
	for _, job := range jobs {
		wg.Add(1)
		go func() {
			defer wg.Done()
			ch <- job
		}()
	}
	wg.Wait() // 全部发送完成后这里返回
}

func main() {
	var started sync.WaitGroup
	before := runtime.NumGoroutine()

	sendAllLeaky([]int{1, 2, 3, 4, 5}, &started)
	started.Wait()
	fmt.Println("baseline:", before, "-> after leaky:", runtime.NumGoroutine())

	// 修复版全部汇合退出,不再新增泄漏;
	// 已泄漏的 goroutine 在进程内仍无法回收
	sendAllFixed([]int{1, 2, 3, 4, 5})
	fmt.Println("after fixed:", runtime.NumGoroutine(), "(泄露的仍在)")
}

How the snippet works

Goroutine Leaks From Unread Channels keeps everything in the functions sendAllLeaky, sendAllFixed and main.

The file repeats itself only inside for _, job := range jobs. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.

Applying it

Entry signature: func sendAllLeaky(jobs []int, started *sync.WaitGroup)

Look for the baseline:, after fixed: prefixes when the file runs; they tie each line to its step.

The demo flow inside main is sendAllLeaky and sendAllFixed — run the file to see it end to end.

Statements that decide the outcome

func sendAllLeaky(jobs []int, started *sync.WaitGroup) {
	ch := make(chan int) // 无缓冲,也没有接收方
	for _, job := range jobs {
		started.Add(1)
		go func() {
			started.Done() // 到达发送点
			ch <- job      // 无人接收:goroutine 永久停在这里
		}()
	}
}
func sendAllFixed(jobs []int) {
	var wg sync.WaitGroup
	ch := make(chan int, len(jobs))
	for _, job := range jobs {
		wg.Add(1)
		go func() {
			defer wg.Done()
			ch <- job
		}()
	}
	wg.Wait() // 全部发送完成后这里返回
}
var started sync.WaitGroup

Interactive Tools for This Topic

FAQ

What does Goroutine Leaks From Unread Channels print when run?
Execute the whole file; each printed line is prefixed with a label like `baseline:`, `after fixed:`.