On Saturday, January 28, 2017 at 10:25:20 PM UTC+8, T L wrote: > > > > On Saturday, January 28, 2017 at 9:33:51 PM UTC+8, C Banning wrote: >> >> From the doc: "The finalizer for obj is scheduled to run at some >> arbitrary time after obj becomes unreachable. There is no guarantee that >> finalizers will run before a program exits, so typically they are useful >> only for releasing non-memory resources associated with an object during a >> long-running program." >> > > > If this is true, then the SetFinalizer function would be much meaningless. > > BTW, it looks both finalizer will get executed if let the program sleep > more than 10us at the beginning: > > package main > > import "time" > import "runtime" > > func main() { > time.Sleep(10 * time.Microsecond) > // if sleep 10 Microsecond here, 2 and 1 will both be out > // if sleep 1 Microsecond here, still only 2 will out > > t1 := new(int) > t2 := new(int) > > runtime.SetFinalizer(t1, func(*int) {println(1)}) > runtime.SetFinalizer(t2, func(*int) {println(2)}) > runtime.GC() > time.Sleep(time.Second * 20) > } > >
BTW 2, it looks that the first finalizer set in a limited escaped time for one-word data pointer will not get executed: package main import "time" import "runtime" type T1 [2]int type T2 [2]int // this program will output both 1 and 2, // but if the length of T2 changes to 1, then 2 will not be output func main() { t1 := new(T1) t2 := new(T2) runtime.SetFinalizer(t1, func(*T1) {println(1)}) runtime.SetFinalizer(t2, func(*T2) {println(2)}) runtime.GC() time.Sleep(time.Second * 1) } > >> >> On Saturday, January 28, 2017 at 6:17:37 AM UTC-7, T L wrote: >>> >>> >>> >>> package main >>> >>> import "time" >>> import "runtime" >>> >>> type T1 struct{ i int } >>> type T2 struct{ i int } >>> >>> func main() { >>> t1 := new(T1) >>> t2 := new(T2) >>> >>> runtime.SetFinalizer(t1, func(*T1) {println(1)}) >>> runtime.SetFinalizer(t2, func(*T2) {println(2)}) >>> runtime.GC() >>> time.Sleep(time.Second * 2) >>> >>> // the program will output: 2 >>> // if I adjust the order of the declarations of t1 and t2, >>> // the program will output: 1 >>> } >>> >>> Why the finalizer for the first declaration will not get called? >>> >> -- 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. For more options, visit https://groups.google.com/d/optout.