Strange deadlock on channel send/receive

Hi. I’ve been wrestling with something very strange in one of my programs recently. Here is a minimal test case that reproduces it:

package main

import (
    "fmt"
)

func main() {
    c := make(chan int)

    go func() {
        i := 0
    	for {
         	c <- i
	        i++
	    }
    }()

    go func() {
        for {
	        fmt.Println(<-c)
        }
    }()

    for {
        //Uncommenting this makes the program run infinitely as expected:
        //fmt.Print("")
    }
}

When I run this program on my machine with the fmt.Print commented out, it gets stuck on the channel send/receive after printing numbers up to around ~260,000. When I uncomment the fmt.Print, it runs forever. Is this somehow expected behavior? I feel like I’m missing something here.

If it’s relevant, I’m running 64-bit Ubuntu 15.10 with version 1.5.1 of go.

replace for { } with select { }. If you write an infinite loop in your code, nothing else will run.

This problem only happens in small test programs like the one you showed because you placed all the work into separate goroutines and then tried to make the main goroutine “sleep” by putting it into an infinite loop. This means no other goroutines are scheduled.

The behaviour of GOMAXPROCS does affect this result, but as you’ve found eventually the infinite loop in the main goroutine will starve everything else of work.

1 Like

Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.