On Fri, Apr 24, 2020 at 9:30 PM T L <tapir....@gmail.com> 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/CAOyqgcW4U90dkpDi6%2B2tdU83LhRXiPSnrCPWrB87G%3DkK1Enh_A%40mail.gmail.com.

Reply via email to