Files
bulma/write_barrier_simulation.go
T

82 lines
1.9 KiB
Go

package main
import (
"fmt"
"sync/atomic"
)
const (
White, Grey, Black = 0, 1, 2
)
type SimObject struct {
ID string
Color int32
Ref *SimObject
}
func (o *SimObject) SetColor(c int32) { atomic.StoreInt32(&o.Color, c) }
func (o *SimObject) GetColor() int32 { return atomic.LoadInt32(&o.Color) }
// 插入屏障:黑色→白色时标灰新对象(概念模拟)
func InsertionBarrier(parent, child *SimObject) bool {
if parent.GetColor() == Black && child.GetColor() == White {
child.SetColor(Grey)
return true
}
return false
}
// 删除屏障:无条件标灰旧引用(概念模拟)
func DeletionBarrier(oldRef *SimObject) bool {
if oldRef != nil && oldRef.GetColor() != Black {
oldRef.SetColor(Grey)
return true
}
return false
}
func colorName(c int32) string {
switch c {
case White:
return "白"
case Grey:
return "灰"
case Black:
return "黑"
}
return "未知"
}
func main() {
fmt.Println("=== 场景1:无屏障 → 漏标风险 ===")
A := &SimObject{ID: "A", Color: Black}
B := &SimObject{ID: "B", Color: White}
A.Ref = B
C := &SimObject{ID: "C", Color: White}
A.Ref = C
fmt.Printf("⚠️ B 状态: %s (孤立白色对象,应被回收)\n", colorName(B.GetColor()))
fmt.Println("\n=== 场景2:插入屏障保护 ===")
A.SetColor(Black)
B.SetColor(White)
A.Ref = B
D := &SimObject{ID: "D", Color: White}
if InsertionBarrier(A, D) {
fmt.Printf("🛡️ [插入] A(黑)→D(白) → D 标灰\n")
}
A.Ref = D
fmt.Printf("✅ D 状态: %s (被屏障保护)\n", colorName(D.GetColor()))
fmt.Println("\n=== 场景3:删除屏障保护 ===")
E := &SimObject{ID: "E", Color: Black}
F := &SimObject{ID: "F", Color: White}
E.Ref = F
G := &SimObject{ID: "G", Color: White}
if DeletionBarrier(E.Ref) {
fmt.Printf("🛡️ [删除] 旧引用 F(白) → F 标灰\n")
}
E.Ref = G
fmt.Printf("✅ F 状态: %s (被屏障重新标灰)\n", colorName(F.GetColor()))
}