GO language: fatal error: all goroutines are asleep - deadlock

前端 未结 2 1780
南方客
南方客 2021-01-31 17:36

Code below works fine with hard coded JSON data however doesn\'t work when I read JSON data from a file. I\'m getting fatal error: all goroutines are asleep - deadlock

2条回答
  •  别跟我提以往
    2021-01-31 17:59

    Thanks for the very nice and detailed explanation Grzegorz Żur. One thing that I want to point it out that typically the func that needs to be threaded wont be in main(), so we would have something like this:

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "io/ioutil"
        "math/rand"
        "os"
        "reflect"
        "regexp"
        "strings"
        "sync"
        "time"
    )
    
    var wg sync.WaitGroup    // VERY IMP to declare this globally, other wise one   //would hit "fatal error: all goroutines are asleep - deadlock!"
    
    func doSomething(arg1 arg1Type) {
         // cured cancer
    }
    
    func main() {
        r := rand.New(rand.NewSource(time.Now().UnixNano()))
        randTime := r.Intn(10)
        wg.Add(1)    
        go doSomething(randTime)
        wg.Wait()
        fmt.Println("Waiting for all threads to finish")
    }
    

    The thing that I want to point it out is that global declaration of wg is very crucial for all threads to finish before main()

提交回复
热议问题