Files
bulma/sysmon_preempt_demo.go
T

38 lines
806 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func main() {
runtime.GOMAXPROCS(1) // 单 P 放大抢占效果
var wg sync.WaitGroup
wg.Add(2)
// 长耗时 CPU 任务(超 10ms 抢占阈值)
go func() {
defer wg.Done()
start := time.Now()
counter := 0
for time.Since(start) < 50*time.Millisecond {
counter++ // 无主动让出 P,触发 sysmon 抢占
}
fmt.Printf("长耗时任务结束,累计计数:%d\n", counter)
}()
// 普通任务(验证调度公平性)
go func() {
defer wg.Done()
for i := 0; i < 10; i++ {
fmt.Printf("普通任务执行第 %d 次(%v\n", i+1, time.Now().Format("15:04:05.000"))
time.Sleep(1 * time.Millisecond)
}
}()
wg.Wait()
fmt.Println("验证完成:sysmon 触发协程抢占,普通任务未被阻塞")
}