
本文介绍一种无需排序的高性能方案:利用预分配切片 + 通道同步,让 16 个 goroutine 并发写入结果后,按 index 字段直接落位到对应位置,最终顺序写入文件。
本文介绍一种无需排序的高性能方案:利用预分配切片 + 通道同步,让 16 个 goroutine 并发写入结果后,按 `index` 字段直接落位到对应位置,最终顺序写入文件。
在 Go 中处理大规模并发任务时,若每个 goroutine 产出带唯一序号(如 index int)的结果,并最终需严格按该序号顺序输出(例如写入文件),排序不是最优解——对百万级结构体调用 sort.Slice 会带来显著内存与时间开销,且违背“数据即有序”的设计前提。
核心思路是:变“事后排序”为“事前定位”。既然每个 output 结构体已携带全局唯一的 index,且你明确知道总结果数(1,000,000),那么可预先分配一个长度为 1000000 的 []string 切片,让每个 goroutine 将 description 直接写入 sorted[index]。这本质是用空间换时间,避免任何比较或交换操作。
以下是完整、健壮的实现方案:
package main
import (
"os"
"sync"
)
type Output struct {
Index int
Description string
}
func worker(id int, ch chan<- Output, wg *sync.WaitGroup) {
defer wg.Done()
// 模拟实际工作:生成若干 Output(此处简化为固定模式)
for i := 0; i < 62500; i++ { // 16 × 62500 = 1,000,000
idx := id*62500 + i
ch <- Output{Index: idx, Description: "Item-" + string(rune('A'+id%26))}
}
}
func writeToFile(filename string, data []string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
for i, desc := range data {
if i > 0 {
f.WriteString(" ") // 按题意空格分隔
}
f.WriteString(desc)
}
f.WriteString("\n")
return nil
}
func main() {
const total = 1_000_000
const numWorkers = 16
ch := make(chan Output, 1024) // 带缓冲通道提升吞吐
var wg sync.WaitGroup
// 启动 16 个 worker goroutine
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go worker(i, ch, &wg)
}
// 预分配结果切片(索引 0 ~ 999999)
sorted := make([]string, total)
// 启动协程等待所有 worker 完成,并关闭信号
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
// 消费通道,按 index 写入预分配切片
for {
select {
case out, ok := <-ch:
if !ok {
return // 通道已关闭(但通常由 done 控制,此分支防御性)
}
if out.Index >= 0 && out.Index < total {
sorted[out.Index] = out.Description
} else {
// 关键健壮性检查:越界则 panic 或记录错误(生产环境建议日志+metrics)
panic("output index out of bounds: " + string(out.Index))
}
case <-done:
// 所有 worker 完成,写入文件
if err := writeToFile("output.txt", sorted); err != nil {
panic("failed to write file: " + err.Error())
}
return
}
}
}✅ 关键优势:
- 零排序开销:时间复杂度 O(N),仅一次遍历写入 + 一次顺序读取;
- 内存局部性好:预分配连续内存,CPU 缓存友好;
- 天然线程安全:各 goroutine 写入不同 slice 索引,无竞争(无需 mutex);
⚠️ 注意事项:
-
必须确保
index全局唯一且在[0, total)范围内,否则将 panic(示例中已加入边界检查); - 若结果总数未知,需改用
map[int]string+ 最终sort.Ints(keys),但会牺牲性能; - 通道缓冲区大小(如
chan Output, 1024)应根据单次产出速率调整,避免 goroutine 阻塞; - 生产环境建议增加超时控制(如
time.After与 select 联用)防止死锁。
最终,output.txt 将严格按 index 递增顺序包含所有 Description,以空格分隔——完全满足题目要求,且性能远超通用排序方案。

















