Question on runtime.Gosched

Hi All,

not very clear of runtime.Gosched. below is what go doc showed. so when I execute runtime.Gosched() in goroutine, it will pass the processor to other goroutine for them to run, and meanwhile it will still keep running? Is there a good example that I can try? Thanks

(base) zwang-mac:cmd2 zwang$ go doc runtime.Gosched
func Gosched()
    Gosched yields the processor, allowing other goroutines to run. It does not
    suspend the current goroutine, so execution resumes automatically.

To keep it simple, concurrency is not parallelism. On a multi-core processors (like those i3, i5, etc.), scheduling a goroutine does not simply means you’re having 2 cores running both main and goroutine process (that’s parallelism). Therefore, both main and goroutine share the same (1) processing core, working in a way that looks like they’re working in parallel (that’s concurrency).

Since both main and goroutine shares the same processing core, passing the core between goroutines (note: main is actually a goroutine itself) often happen. This is why runtime.Gosched() is made available.

Note that if your concurrency codes are well planned and executed (e.g. handling channel I/O nicely), you rarely need to call runtime.Gosched().

You can try to re-invent channel feature in Go using mutex locks. It might be waste of time but that’s one case I witnessed its usage before.

1 Like

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