How to create deadlock in Golang

Operating systems utilize multiprocessing and multitasking to complete tasks more quickly and to complete processes.

Deadlock arises when two processes operate at the same time and block one another's routes. It is a situation, in other words, in which a process does not receive the resources it needs to finish.

An example of a deadlock


Following are the conditions that occur in a deadlock state:

  1. The resource is controlled by one process alone.

  2. Each process waits for the other process to free its resources so it could complete its task.

  3. Before a procedure has finished running, it is requested by another.

  4. Each process in the chain holds a resource.

Let's look into an example of a program for a better understanding.

package main
func main() {
goChannel := make(chan int)
goChannel2 := make(chan int)
goChannel <- 1
goChannel2 <- 2
}

Explanation

  • Lines 4–5: We create two channels with the name Channel and Channel2 .

  • Lines 7–8: Both channels got deadlocked because of senders.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved