4

How exactly are goroutines scheduled? Is it some sort of function interception mechanism? Also if I run the program on one CPU will the results be the same if I run the program twice?

Curious
  • 20,870
  • 8
  • 61
  • 146
  • The scheduler runs when your goroutine is blocked from working (like when waiting for I/O or on a channel/`sync` operation), and occasionally when you call a function. Some scheduling choices are pseudorandom (it's explicit in the spec for the `select` statement) so no, you're not guaranteed the same results for repeat runs if running with `GOMAXPROCS=1`. – twotwotwo Dec 28 '15 at 21:55
  • You also don't want to rely on any of that; how the scheduler works now isn't necessarily how it'll work in the future. You might find [this recent question](http://stackoverflow.com/questions/34192352/are-channel-sends-preemption-points-for-goroutine-scheduling/34192397#34192397) relevant on that front. – twotwotwo Dec 28 '15 at 21:59
  • Goroutines themselves aren't deterministic, if that's what you're asking. They also have nothing to do with os threads, pthreads or cpus . Unless you have a specific question, asking for a full rundown of the current gc scheduler implementation isn't really a valid SO question. – JimB Dec 28 '15 at 21:59
  • @JimB Since I asked an implementation question I think Goroutines do have a lot to do with pthreads in that on most systems a CPU in Go is implemented as a pthread and different Goroutines are multiplexed on that cpu. I am in the process of implementing a weird (because I made all the design decisions) thread library and I was looking for a really high level explanation of how Go does this for inspiration. – Curious Dec 28 '15 at 22:08
  • 1
    You seem to understand that M goroutines are cooperatively scheduled over N os threads. Are you looking for the actual implementation details? Does something like this help? http://www.cs.columbia.edu/~aho/cs6998/reports/12-12-11_DeshpandeSponslerWeiss_GO.pdf (the overview is the same, but as with all implementation details, the implementation changes and this is out of date) – JimB Dec 28 '15 at 22:40
  • You might also be interested in the source of [libmill](https://github.com/sustrik/libmill), which aims for Go-like concurrency in C, or [Go's runtime](https://github.com/golang/go/tree/master/src/runtime). "How exactly are goroutines scheduled?" is the sort of prompt that one could likely write a fascinating series of blog posts or a solid conference talk about, but in looking into that general question or working on your library, you might have specific questions that are a good size for Stack Overflow. – twotwotwo Dec 29 '15 at 04:09
  • Thank you! I will look into these things! I have been since yesterday :) I will close the question soon. Just want to wait to see if someone else has something to say – Curious Dec 29 '15 at 06:09

0 Answers0