WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Advanced · question 43 of 100

How can you perform deadlock detection in Go?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

Deadlock detection in Go can be performed using various approaches, some of which are:

1. Go Race Detector:

Using the Go race detector is a good starting point for detecting potential deadlocks caused by race conditions. It does not detect deadlocks directly, but it can help in identifying them indirectly. To use the race detector, compile and run your program with the ‘-race‘ flag:

go build -race mypackage
./mypackage

2. Using Go’s built-in deadlock detection: Go has a built-in deadlock detection mechanism that can report when your program contains a deadlock. By default, it might not be sufficient for complex scenarios, but it can work effectively for simple cases. When the deadlock detector detects a goroutine waiting on a channel, it prints the error message and exits the program.

3. Use ‘go-deadlock‘ package: There’s an external deadlock detection package called ‘go-deadlock‘, which is more powerful and flexible than the built-in deadlock detector. It can be found at https://github.com/sasha-s/go-deadlock

To use this package, you’ll need to replace standard Go synchronization primitives like ‘sync.Mutex‘, ‘sync.RWMutex‘, and ‘sync.WaitGroup‘ with their ‘deadlock‘ counterparts provided by the package. For example, if you have a ‘sync.Mutex‘ in your code, replace it with ‘deadlock.Mutex‘:

package main
import (
 "fmt"
 "time"
 "github.com/sasha-s/go-deadlock"
)

var mu deadlock.Mutex
var data int

func increment() {
 mu.Lock()
 defer mu.Unlock()
 data++
 fmt.Printf("Data: %dn", data)
}

func main() {
 go increment()
 go increment()
 time.Sleep(time.Second)
}

After making this change, ‘go-deadlock‘ will print detailed information about deadlocks when it detects one, including stack traces of involved goroutines.

By using these techniques, you’ll be able to detect and fix deadlocks in your Go programs. However, always remember that prevention is better than cure. Designing your code with proper synchronization mechanisms, using idiomatic Go techniques like channels, and avoiding circular dependencies between resources can help you minimize deadlocks in your programs.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics