使用 goroutine 时出现死锁

我有一个程序可以做两件事:

  • 读取日志条目并创建logEntry对象

  • 处理每个logEntry实例

在这里,读取由单独的 goroutine 完成,所有读取条目的处理由单个 goroutine 完成。

我正在使用等待组——wg确保在程序退出之前读取所有日志条目,并使用信号通道——done确保日志条目的处理完成。

等待组按预期工作,但是当我调用<-done以确保程序仅在处理读取的日志文件后退出时,它会抛出错误fatal error: all goroutines are asleep - deadlock!

有人可以解释为什么会发生这种情况以及如何解决上述错误吗?


慕无忌1623718
浏览 135回答 1
1回答

肥皂起泡泡

在你的情况下,你正在听linesChan,但没有关闭它。当所有数据都通过时,您需要关闭此通道。done <- true不会被执行。但是这里不需要同步频道,sync.WaitGroup{}就足够了。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")type logEntry struct {&nbsp; &nbsp; lines&nbsp; &nbsp; &nbsp; []string&nbsp; &nbsp; created_at string&nbsp; &nbsp; line_count int}var wg sync.WaitGroupfunc main() {&nbsp; &nbsp; linesChan := make(chan (logEntry))&nbsp; &nbsp; // Process entries from lines&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; for c := range linesChan {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(100 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%v\n", c)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; // Read lines&nbsp; &nbsp; for i := 1; i <= 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go func(i int, linesChan chan (logEntry)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; read(i, linesChan)&nbsp; &nbsp; &nbsp; &nbsp; }(i, linesChan)&nbsp; &nbsp; }&nbsp; &nbsp; // Wait till all the files are read&nbsp; &nbsp; wg.Wait()}func read(count int, channel chan (logEntry)) {&nbsp; &nbsp; fmt.Println(count, "read")&nbsp; &nbsp; channel <- logEntry{&nbsp; &nbsp; &nbsp; &nbsp; line_count: count,&nbsp; &nbsp; }&nbsp; &nbsp; wg.Done()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go