go sched
package main
import (
"fmt"
"io/ioutil"
"runtime"
"sync"
"time"
)
func main() {
runtime.GOMAXPROCS(1) // 如果是多核就不一定能看到调度的效果了
wg := new(sync.WaitGroup)
wg.Add(4)
go func() {
defer wg.Done()
fmt.Println("start func alpha")
runtime.Gosched()
fmt.Println("done func alpha")
}()
//IO操作可能会导致go routiner 让出线程(strings或bytes的NewReader不会)
go func() {
defer wg.Done()
fmt.Println("start func beta")
err := ioutil.WriteFile("file.txt", []byte(`
go sched test\n
go sched test\n
go sched test\n
go sched test\n
go sched test\n
`), 0644)
if err != nil {
panic(err)
}
fmt.Println("done func beta")
}()
// wait 操作也会导致让出线程
go func() {
defer wg.Done()
fmt.Println("start func Gamma")
time.Sleep(time.Second)
fmt.Println("done func Gamma")
}()
go func() {
defer wg.Done()
fmt.Println("start func omega")
runtime.Gosched()
fmt.Println("done func omega")
}()
wg.Wait()
}