With time.Sleep, it always prints: > 31 > 37 > 47 > 47 > 37 > 31 >
Why is each of the finalizers called twice? On Saturday, April 25, 2020 at 1:08:43 AM UTC-4, Ian Lance Taylor wrote: > > On Fri, Apr 24, 2020 at 9:30 PM T L <tapi...@gmail.com <javascript:>> > wrote: > > > > The following program might print: > > > >> 31 > >> 37 > >> 47 > >> 47 > >> 37 > >> 31 > > > > > > or > > > >> 31 > >> 37 > >> 47 > >> 47 > > > > > > but with the highest possibility to print > > > >> 31 > >> 37 > >> 47 > > > > > > Is not normal? > > > > > > package main > > > > import ( > > "fmt" > > "math/rand" > > "runtime" > > "time" > > "unsafe" > > ) > > > > type Foo struct { > > x int > > a int > > } > > > > func main() { > > for i := 0; i < 3; i++ { > > f := NewFoo(i) > > println(f.a) > > } > > > > runtime.GC() > > > > time.After(time.Second) > > } > > > > func do(i *uint) { > > runtime.SetFinalizer(i, func(f *uint) { > > fmt.Println(*f) > > }) > > } > > > > //go:noinline > > func NewFoo(i int) *Foo { > > f := &Foo{a: rand.Intn(50)} > > > > do((*uint)(unsafe.Pointer(&f.a))) > > > > return f > > } > > Finalizers are not guaranteed to run. > > That said, I'm not sure why you are calling time.After. That doesn't > make finalizers any more likely to run. You'll probably see fairly > reliable results if you change that to call time.Sleep instead. > > Ian > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/68c17055-b1ed-4b26-a6d2-63c02e1d8ea0%40googlegroups.com.