How to detect deadlocks in a Go program?

74 views Asked by At

In the below 2 programs, all existing go-routines are blocked.

package main

import (
    "fmt"
)

func worker() {

    fmt.Printf("some work\n")

}

func main() {

    ch := make(chan int)

    go worker()
    <-ch

}

package main

import (
    "fmt"
    "runtime"
    "sync"
)

func main() {

    // wg is used to manage concurrency
    var wg sync.WaitGroup
    wg.Add(2)

    fmt.Println("Start Goroutines")

    // Create a goroutine from the lowercase function
    go func() {
        lowercase()
        // wg.Done() // Line 25
    }()

    // Create a goroutine from the uppercase function
    go func() {
        uppercase()
        wg.Done()
    }()

    // Wait for the goroutines to finish
    // fmt.Printf("Waiting for Finish")
    wg.Wait()    // Line 42

    fmt.Println("\n Terminating program")
}

// lowercase displays the set of lowercase letters three times
func lowercase() {

    // Display the alphabet three times
    for count := 0; count < 3; count++ {
        for r := 'a'; r <= 'z'; r++ {
            fmt.Printf("%c ", r)
        }
    }
}

// uppercase displlays the set of uppercase letters three times.
func uppercase() {

    // Display the alphabet three times
    for count := 0; count < 3; count++ {
        for r := 'A'; r <= 'Z'; r++ {
            fmt.Printf("%c ", r)
        }
    }
}

$ go version
go version go1.20.2 linux/amd64
$ go build   -o main cmd/test/main.go
$ go run -race cmd/test/main.go
some work
^Csignal: interrupt
$

Does Go compiler provide flag options to detect deadlock?

0

There are 0 answers