且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Julia 中编写模块 finalize 方法的正确方法是什么?

更新时间:2022-12-24 19:04:52

IMHO, workspace takes no ***ers and in addition the finalizer works well only on user-defined and composite types.

I've performed some tests. Have a look at my results:

julia> type Foo
         x
         Foo(x) = begin obj = new(x); finalizer(obj,(o) -> println("The end.")); return obj end
       end

julia> Foo(1)

julia> workspace()

julia> gc()
Module the end.error in running finalizer: ErrorException("task switch not allowed from inside gc finalizer")
The end.error in running finalizer: ErrorException("task switch not allowed from inside gc finalizer")

Another test with object defined inside module scope:

julia> module FinMod

        type T  
            x::Int  
        end

        finalizer(T(1), (t) -> println("Module the end."))
       end
FinMod

julia> FinMod
FinMod

julia> workspace()

julia> gc()
Module the end.error in running finalizer: ErrorException("task switch not allowed from inside gc finalizer")

What about functions(first-class objects)?

julia> function foo()  println("I'm foo") end
foo (generic function with 1 method)

julia> finalizer(foo, (f) -> println("foo function is dead now."))

julia> foo
foo (generic function with 1 method)

julia> workspace()

julia> foo
ERROR: UndefVarError: foo not defined

julia> gc()

julia> #nothing happened

So, to summarize: In my opinion workspace doesn't call finalize. The finalizer function works OK only for user-defined and composite types. It does not work for Module or Function.

Update: I remembered that workspace rewrites previous Main module into LastMain. So even if our module is not accesible from Main it's is still alive inside LastMain scope (the same works for the function which I used above).