首次提交:初始化项目代码
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TestData struct{ Value int }
|
||||
|
||||
func main() {
|
||||
var gcTriggered int32
|
||||
blackObj := &struct{ ref *TestData }{}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
whiteObj := &TestData{Value: 42}
|
||||
runtime.SetFinalizer(whiteObj, func(o *TestData) {
|
||||
if atomic.LoadInt32(&gcTriggered) == 1 {
|
||||
fmt.Printf("❌ 验证失败:whiteObj 被回收!值=%d\n", o.Value)
|
||||
}
|
||||
})
|
||||
blackObj.ref = whiteObj // 触发写屏障(由运行时自动处理)
|
||||
fmt.Println("✅ 业务线程:黑色对象引用新白色对象")
|
||||
close(done)
|
||||
}()
|
||||
|
||||
atomic.StoreInt32(&gcTriggered, 1)
|
||||
runtime.GC() // 触发含并发标记的 GC
|
||||
<-done
|
||||
|
||||
fmt.Println("✅ 验证通过:新对象存活(写屏障将其标灰纳入扫描)")
|
||||
fmt.Println("💡 原理:运行时写屏障拦截赋值,将 whiteObj 标灰")
|
||||
}
|
||||
Reference in New Issue
Block a user