What is a deadlock?
sobes.tech AI
Answer from AI
Deadlock (mutual blocking) is a situation in a multithreaded or multiprocess environment where two or more processes (or threads) permanently block each other, waiting for resources held by each other.
Example: Thread A has acquired resource 1 and is waiting for resource 2, while Thread B has acquired resource 2 and is waiting for resource 1. Neither can continue working — a deadlock occurs.
In Go, deadlock can occur, for example, if a goroutine tries to send or receive data from a channel, but another goroutine is not ready to accept or send data, and all goroutines are blocked.
Example of deadlock in Go:
func main() {
ch := make(chan int)
ch <- 1 // Trying to send to a channel without a receiver — the program will block
}
Here, the program will hang because there is no goroutine reading from the channel, and the send operation blocks forever.
To prevent deadlocks, it is important to design interactions between threads correctly and to use synchronization mechanisms carefully.