Skip to content

Instantly share code, notes, and snippets.

@x1ah
Created October 16, 2019 03:24
Show Gist options
  • Save x1ah/a225ed652ba18c587839a80f3f8f798a to your computer and use it in GitHub Desktop.
Save x1ah/a225ed652ba18c587839a80f3f8f798a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
// 返回 <-chan int 表示只读 channel
func waitGroupDeadLockDemo() <-chan int {
outChannel := make(chan int)
nGoroutine := 20
var wg sync.WaitGroup
wg.Add(nGoroutine)
for i := 0; i < nGoroutine; i++ {
// 这里复制一份 i 的值传进去,否则最后是 i 的引用,即 nGoroutine 的值
go func(iCopy int) {
defer wg.Done()
outChannel <- iCopy
}(i)
}
// 错误写法
// outChannel 是无缓冲 channel,读写同步,这里 wait 阻塞了,
// 没有地方读了,所以导致整个进程阻塞了,发生死锁,正确的做法是
// 起一个 goroutine 去 wait,这样不阻塞主进程,只有那个 goroutine 会阻塞
//wg.Wait()
//close(outChannel)
// 正确的写法
go func() {
wg.Wait()
close(outChannel)
}()
return outChannel
}
func main() {
for res := range waitGroupDeadLockDemo() {
fmt.Printf("%3d", res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment