Hacker News new | past | comments | ask | show | jobs | submit login

Go's scheduler is not preemptive, which means that sometimes Goroutines can hog the processor. If loops don't contain function calls, or allocate memory, or other preemption points, they can prevent other goroutines from running. A simple example is:

    package main
    func main() {
      go println("I ran")
      for {}
    }
If you run with:

    GOMAXPROCS=1 go run main.go
It will never print the statement. This doesn't come up frequently in practice, but Linux does not suffer from this case.



I heard Go got a preemptive scheduler recently.

EDIT: https://github.com/golang/go/issues/24543


This just happened to me. I wanted to run a goroutine and then not exit the program, so I ran an empty for loop and it didn’t work. Would a for{ continue } have work?


`for { continue }` is semantically equivalent to `for {}` since the closing bracket of the loop block implies a `continue`.

As a sibling correctly notes, `select {}` is what you want to do instead. You need to do something that can block the goroutine in such a way that control returns to the scheduler. Selecting is one of those ways.


You can use select{} to block forever and yield the goroutine.


Yield?


Interesting find.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: