本文旨在探讨go
并发编程
中,基于通道(channel)实现工作池时可能遇到的死锁问题。通过分析一个典型的死锁案例,文章将揭示其根本原因在于未能正确关闭发送数据的通道。随后,文章将提供一个经过优化的解决方案,演示如何利用通道关闭机制优雅地终止工作协程,并介绍
go语言
中更推荐的并发同步模式,以构建健壮、高效的并发系统。
理解Go并发中的死锁根源
在Go语言中,协程(goroutine)和通道(channel)是实现并发的核心机制。当构建一个生产者-消费者模型,例如工作池系统时,生产者将任务发送到通道,消费者(工作协程)从通道接收任务并处理。然而,如果处理不当,这种模式很容易导致死锁。
考虑以下场景:一个主协程负责填充任务队列并启动多个工作协程,然后等待所有工作协程完成。工作协程从队列通道中读取任务,处理完毕后向一个“完成”通道发送信号。如果任务队列通道在所有任务发送完毕后没有被关闭,那么工作协程在处理完所有现有任务后,会持续尝试从一个永远不会有新数据写入、也永远不会被关闭的通道中读取数据。这将导致工作协程永久阻塞。同时,主协程在等待工作协程发送完成信号时,也会因为工作协程被阻塞而无法收到信号,最终导致主协程也阻塞,从而引发整个程序的死锁。
以下是导致死锁的典型代码示例及其运行日志:
运行上述代码,会得到类似以下日志,最终程序会因死锁而崩溃:
从日志中可以看到,主协程启动了一个工作协程并等待其完成。工作协程处理了所有任务后,试图再次从 queue 通道读取,但 queue 通道既没有新数据,也没有被关闭,导致工作协程阻塞。因此,工作协程永远无法执行到 waiters <- true 这一行,主协程也就会永远阻塞在 <-waiters,最终导致死锁。
解决方案:正确关闭通道
解决上述死锁的关键在于,当所有任务都已发送到 queue 通道后,必须显式地关闭该通道。通道关闭后,接收方在尝试读取时,如果通道中已无数据,ok 变量将返回 false,从而允许工作协程优雅地退出循环。
改进后的 fillQueue 函数:
go语言参考手册 中文CHM版
Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易。本文给大家带来Go参考手册,需要的可以来下载! Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发,后来还加入了Ian Lance Taylor, Russ Cox等人,并最终于2009年11月开源,在2012年早些时候发布了Go 1稳定版本。现在Go的开发已经是完全开放的,并且拥有一个活跃的社区。 Go 语言特色 简洁、快速、安全 并行、有趣、开源 内存管理、v数组安全、编译
下载
通过添加 close(queue),工作协程在处理完所有任务后,能够通过 entry, ok := <-queue 语句检测到通道已关闭(ok 为 false),从而跳出循环,执行 waiters <- true,通知主协程其已完成任务。这样,主协程就能顺利接收到所有完成信号,避免死锁。
更Go语言风格的实践:使用 for...range 和 sync.WaitGroup
Go语言提供了更简洁和推荐的通道迭代方式以及协程
同步机制
。
1. 使用 for...range 遍历通道
for...range 循环可以直接迭代通道,它会自动处理通道关闭的情况,并在通道关闭且无数据时退出循环,使代码更加简洁。
2. 使用 sync.WaitGroup 进行协程同步
sync.WaitGroup 是Go
标准库
中用于等待一组协程完成的更常用和推荐的工具。它比手动管理 waiters 通道更加简洁和安全。
运行 fillQueueWithWaitGroup 函数,程序将正常执行并退出,不会出现死锁。
注意事项与最佳实践
谁来关闭通道?
通常,应该由发送方在所有数据发送完毕后关闭通道。接收方不应该关闭通道,因为这可能导致在发送方仍然尝试发送数据时关闭通道,从而引发运行时错误(panic)。
只关闭一次通道
重复关闭一个已关闭的通道也会导致运行时错误(panic)。确保通道只被关闭一次。
缓冲通道的选择
带缓冲的通道可以解耦生产者和消费者,提高并发效率。如果缓冲区已满,发送方会阻塞;如果缓冲区为空,接收方会阻塞。
for...range vs value, ok := <-channel
对于只需要消费通道中所有数据的场景,for...range 是更简洁、更Go语言风格的选择。如果需要根据 ok 状态执行额外逻辑(例如,区分通道关闭和通道中无数据),则 value, ok := <-channel 更适用。
错误处理
在实际应用中,工作协程中的任务处理可能会失败。需要考虑如何将错误信息返回给主协程或日志记录系统。
参考 Effective Go
Go语言官方文档中的 Effective Go 章节提供了许多关于Go语言编程的最佳实践和惯用法,强烈推荐阅读,以深入理解Go的并发模型和其他核心特性。
总结
在Go语言中构建并发系统时,通道是强大的通信工具,但其使用需要谨慎。理解通道关闭的语义及其对接收方的影响至关重要。通过在所有数据发送完毕后正确关闭通道,我们可以确保工作协程能够优雅地终止,避免死锁。同时,采用 for...range 遍历通道和 sync.WaitGroup 进行协程同步是Go语言中更推荐和更具可读性的并发编程模式,有助于构建健壮、高效且易于维护的并发应用程序。
package main
import (
"fmt"
"sync"
"time" // 引入time包用于模拟工作
)
type entry struct {
name string
}
type myQueue struct {
pool []*entry
maxConcurrent int
}
// process 是工作协程函数
func process(queue chan *entry, waiters chan bool) {
for {
// 尝试从queue通道接收数据
entry, ok := <-queue
if !ok {
// 如果通道已关闭且没有数据,ok会是false,此时协程应退出
break
}
fmt.Printf("worker: %s processing %s\n", time.Now().Format("15:04:05"), entry.name)
entry.name = "processed_" + entry.name // 模拟处理
time.Sleep(100 * time.Millisecond) // 模拟工作耗时
}
fmt.Println("worker finished")
waiters <- true // 通知主协程此工作协程已完成
}
// fillQueue 负责填充队列并启动工作协程
func fillQueue(q *myQueue) {
queue := make(chan *entry, len(q.pool)) // 创建带缓冲的任务队列通道
for _, entry := range q.pool {
fmt.Println("push entry: " + entry.name)
queue <- entry // 填充任务
}
fmt.Printf("entry cap: %d\n", cap(queue))
var total_threads int
if q.maxConcurrent <= len(q.pool) {
total_threads = q.maxConcurrent
} else {
total_threads = len(q.pool)
}
waiters := make(chan bool, total_threads) // 创建带缓冲的完成信号通道
fmt.Printf("waiters cap: %d\n", cap(waiters))
var threads int
for threads = 0; threads < total_threads; threads++ {
fmt.Println("start worker")
go process(queue, waiters) // 启动工作协程
}
fmt.Printf("threads started: %d\n", threads)
// 等待所有工作协程完成
for ; threads > 0; threads-- {
fmt.Println("wait for thread")
ok := <-waiters // 阻塞等待工作协程发送完成信号
fmt.Printf("received thread end: %b\n", ok)
}
fmt.Println("All workers finished and main goroutine exited.")
}
func main() {
// 示例用法
q := &myQueue{
pool: []*entry{
{name: "name1"},
{name: "name2"},
{name: "name3"},
},
maxConcurrent: 1, // 假设最大并发数为1
}
fillQueue(q)
}
push entry: name1
push entry: name2
push entry: name3
entry cap: 3
waiters cap: 1
start worker
threads started: 1
wait for thread
worker: 15:04:05 processing name1
worker: 15:04:05 processing name2
worker: 15:04:05 processing name3
fatal error: all goroutines are asleep - deadlock!func fillQueue(q *myQueue) {
queue := make(chan *entry, len(q.pool))
for _, entry := range q.pool {
fmt.Println("push entry: " + entry.name)
queue <- entry
}
// 关键一步:在所有任务发送完毕后关闭通道
close(queue)
fmt.Printf("entry cap: %d\n", cap(queue))
var total_threads int
if q.maxConcurrent <= len(q.pool) {
total_threads = q.maxConcurrent
} else {
total_threads = len(q.pool)
}
waiters := make(chan bool, total_threads)
fmt.Printf("waiters cap: %d\n", cap(waiters))
var threads int
for threads = 0; threads < total_threads; threads++ {
fmt.Println("start worker")
go process(queue, waiters)
}
fmt.Printf("threads started: %d\n", threads)
for ; threads > 0; threads-- {
fmt.Println("wait for thread")
ok := <-waiters
fmt.Printf("received thread end: %b\n", ok)
}
fmt.Println("All workers finished and main goroutine exited.")
}// process 是工作协程函数,使用for...range遍历通道
func processImproved(queue chan *entry, waiters chan bool) {
for entry := range queue { // 循环会自动在通道关闭且无数据时退出
fmt.Printf("worker: %s processing %s\n", time.Now().Format("15:04:05"), entry.name)
entry.name = "processed_" + entry.name
time.Sleep(100 * time.Millisecond)
}
fmt.Println("worker finished")
waiters <- true // 通知主协程此工作协程已完成
}package main
import (
"fmt"
"sync"
"time"
)
type entry struct {
name string
}
type myQueue struct {
pool []*entry
maxConcurrent int
}
// processWithWaitGroup 是使用sync.WaitGroup的工作协程函数
func processWithWaitGroup(queue chan *entry, wg *sync.WaitGroup) {
defer wg.Done() // 协程退出时调用wg.Done()
for entry := range queue {
fmt.Printf("worker: %s processing %s\n", time.Now().Format("15:04:05"), entry.name)
entry.name = "processed_" + entry.name
time.Sleep(100 * time.Millisecond)
}
fmt.Println("worker finished")
}
// fillQueueWithWaitGroup 负责填充队列并启动工作协程,使用sync.WaitGroup
func fillQueueWithWaitGroup(q *myQueue) {
queue := make(chan *entry, len(q.pool))
var wg sync.WaitGroup // 声明一个WaitGroup
// 生产者:填充任务
for _, entry := range q.pool {
fmt.Println("push entry: " + entry.name)
queue <- entry
}
close(queue) // 任务填充完毕后关闭通道
var total_threads int
if q.maxConcurrent <= len(q.pool) {
total_threads = q.maxConcurrent
} else {
total_threads = len(q.pool)
}
// 消费者:启动工作协程
for i := 0; i < total_threads; i++ {
wg.Add(1) // 每启动一个协程,计数器加1
fmt.Println("start worker")
go processWithWaitGroup(queue, &wg)
}
fmt.Printf("threads started: %d\n", total_threads)
wg.Wait() // 阻塞等待所有协程完成(计数器归零)
fmt.Println("All workers finished and main goroutine exited.")
}
func main() {
q := &myQueue{
pool: []*entry{
{name: "name1"},
{name: "name2"},
{name: "name3"},
{name: "name4"},
{name: "name5"},
},
maxConcurrent: 2, // 示例:2个并发工作协程
}
fillQueueWithWaitGroup(q)
}
push entry: name1
push entry: name2
push entry: name3
push entry: name4
push entry: name5
start worker
start worker
threads started: 2
worker: 15:04:05 processing name1
worker: 15:04:05 processing name2
worker: 15:04:05 processing name3
worker: 15:04:05 processing name4
worker: 15:04:05 processing name5
worker finished
worker finished
All workers finished and main goroutine exited.