Golang on VS Code and DeadLock



  • I'm reading the English by video. The lecturer uses the IDE from JetBrains and, in examining the subject of the deadlock in the next code, he has a mistake:

        package main
    

    import (
    "fmt"
    "math/rand"
    "sync"
    "time"
    )

    type Worker struct {
    id int
    die chan bool
    *sync.WaitGroup
    }

    func (w *Worker) DoWork() <-chan string {
    c := make(chan string)
    go func() {
    for {
    select {
    case <-time.After(time.Duration(rand.Intn(1000)) * time.Millisecond):
    c <- fmt.Sprintf("Worker #%d, do some work - %d", w.id, rand.Intn(100))
    case <-w.die:
    fmt.Println("Finish work")
    return
    }
    }
    }()
    return c

    }
    func (w *Worker) Die() {
    fmt.Printf("Worker die %d\n", w.id)
    w.die <- true
    w.Done()
    close(w.die)
    }
    func NewWorker(id int, wg *sync.WaitGroup) *Worker {

    die := make(chan bool,1)  // &lt;-- Если канал не буферизированный, то будет deadlock
    wg.Add(1)
    return &amp;Worker{id, die, wg}
    

    }

    func main() {
    var wg sync.WaitGroup

    w1 := NewWorker(1, &amp;wg)
    w2 := NewWorker(2, &amp;wg)
    
    res1 := w1.DoWork()
    res2 := w2.DoWork()
    
    for i := 0; i &lt; 6; i++ {
        fmt.Println(&lt;-res1)
        fmt.Println(&lt;-res2)
    }
    w1.Die()
    w2.Die()
    
    wg.Wait()
    

    }

    fatal error: all goroutines are asleep - deadlock!

    I don't make such a mistake on VS Code. Just the flow stops answering and everything.
    How do you include this error on the VS Code?

    golang:
    go version go1.17.2 windows/amd64
    VS code:
    Версия: 1.62.2 (user setup)
    Фиксация: 3a6960b964327f0e3882ce18fcebd07ed191b316
    Дата: 2021-11-11T20:56:38.428Z
    Electron: 13.5.2
    Chrome: 91.0.4472.164
    Node.js: 14.16.0
    V8: 9.1.269.39-electron.0
    ОС: Windows_NT x64 10.0.19043



  • The answer is that the VS Code TC launched the F-5 button, that's the cooler. The sweet comes to a fatal error and stops. The TC did not notice that the shell of the refrigeration showed the programme stop. If you press the "live" button, the program will make a mistake and end.

    If you start a program Ctrl-F5the program will be launched without retrieval, and it will reach the end (i.e., reports of grandfather) without stopping.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2