Gc() and WeakKeyDict does not work with local variable in function

Hi, I am use WeakKeyDict for manage memory for parallel implementations.
I found it does not work properly the object created and assigned locally in a function.
Below is an example.
The results of main function and the code below it should be the same.
But, WeakKeyDict in the main function does not clean objects that do not have a variable pointing themselves.
And one more problem is that WeakKeyDict cleans garbage data only if gc called twice.

type Constructor
  id::Int
 end
 
d = WeakKeyDict()
   
function main()
  global d
  a = Constructor(1)
  d[a] = a.id
  a = 0
  gc()
  gc()
  println(d)
end

main()

a = Constructor(1)
d[a] = a.id
a = 0
gc()
gc() # if gc once does not remove... 
println(d)

There’s no guarantee that variables becomes unreachable when you do a = 0.

I do not understand what you mentioned.
In the main function, intuitively if a = 0, there is no pointers or variables pointing to Contructor(1).

In addition, why does the below case (code in the global scope) work?
Can you explain me in more detail?

This is not true. The assignment to local variable a = 0 has no semantic significance what so ever about when the Constructor(1) object can be free’d. The compiler+runtime is free to free it before that assignment or not free it after the assignment. Both behavior are valid. Elongating the lifetime is indeed sometimes a performance issue so the compiler is being improved on reducing these cases. However, the performance is NOT optimized for freeing objects eagerly (which is usually NOT a good thing) so it will not be guaranteed when a local variable reference is considered dead.

The global one actually is well defined. Assignments to global variable has well defined semantics with regard to reachability.

Thank you for your kind response!!!