Do we still need runtime.Gosched() in go 1.19?

263 Views Asked by At

Regarding this post As that post mentioned, we don't need to put runtime.Gosched() anymore, since Go 1.15

But I still got the issue in Go 1.19. Concisely,

  • I don't use runtime.Goshed()
  • I used runtime.GOMAXPROCS(2)

If I put runtime.Ghoshed(), it work flawlessly. But without that, it seems Go executes a goroutine entirely before move to another.

Here is the code

func say(s string) {
    for i := 0; i < 5; i++ {
        fmt.Println(s)
    }
}

func main() {
    runtime.GOMAXPROCS(2)

    go say("Hello")
    say("World")
    time.Sleep(time.Second)
}

Output (this seems cooperative, not preemptive )

Hello
Hello
Hello
Hello
Hello
World
World
World
World
World

Expected something like this

Hello
World
Hello
World
Hello
World
Hello
World
Hello

My CPU

fmt.Println(runtime.NumCPU())
Output: 12
1

There are 1 best solutions below

0
feiniks On

We don't need to put runtime.Gosched() anymore. Your test gives you the illusion that one thread runs and then executes another thread. This is because your cpu runs faster. You can simply add a sleep, and the output of the test will be a normal concurrent output.

package main
import "fmt"
import "time"
//import "runtime"

func say(s string) {
    for i := 0; i < 5; i++ {
        fmt.Println(s)
        time.Sleep(time.Second)
    }
}

func main() {
    //runtime.GOMAXPROCS(2)

    go say("Hello")
    say("World")
    time.Sleep(10*time.Second)
}