go deadlock

tags: learning programming

content

  • different threads are waiting on each other to release some resources
  • they’re blocked indefinitely, none of them can proceed

one simple deadlock:

func main() {
	ch := make(chan int)
	ch <- 1
	fmt.Println(<-ch)
}
  • this channel ch here is not buffered
    • meaning when there’s a value being sent to it, there’s no buffer to store it
    • so there has to be another thread that’s reading it concurrently
    • otherwise, the thread writing it will get blocked (in this case, the main thread)
    • so the line ch <- 1 is getting blocked, causing fmt.Println(<-ch) unable to be reached
  • either we make the channel buffered by ch := make(chan int, 1)
  • or we make 2 threads, one read one write:
func main() {
	ch := make(chan int)
	go func() {
		ch <- 1  // writing into unbufferred channel here
	}()
	fmt.Println(<-ch). // reading unbufferred channel here
}

up

thread-safety go-channel-basics

down

reference