My question is about garbage-collection in general but I'm going to use python as an example. But I need to build up my question first with some facts, or at least what I think are facts, feel free to correct me.
The CPython implementation of python is a virtual machine written in C which contains a garbage-collector. But Jython, which is an implementation of python that runs on JVM, does not need to implement a garbage-collector, because all it's doing is compiling python to java bytecode that the JVM is going to run and JVM already has a garbage-collector.
But suppose I want to implement a python VM using Golang. As far as I know, when you compile your Go code, the Go compiler attaches a runtime to your compiled binary which contains a garbage-collector, so when I compile my VM, it's going to contain the Go runtime and garbage-collector. Does that mean that if I write a python VM in Golang, I won't need to implement a garbage-collector?
Thanks
CodePudding user response:
The answer depends on how you implement the Python VM.
Usually, an interpreter will need to keep track of all the symbols declared in a program. Thus even if the program removes all the references to an object, the runtime (Go program) will keep a reference to it, preventing it from being garbage collected. Such an implementation will require a custom garbage collector.
A custom garbage collector can be avoided if your interpreter does reference counting for every symbol, and releases it as soon as all the references to it are gone. In that case, the Go garbage collector will collect it eventually. Reference counting is usually easier to implement, but may be less efficient for long-running programs.
CodePudding user response:
The go garbage collector will understand the structures of your VM, not about the code that the VM itself will handle.
So the answer is: you still need to implement a garbage collector for your VM
For instance: imagine a very simple Virtual Machine with some memory and few instructions. The memory can be a slice of bytes in Go. But will ne one slice, used from begin to end. The GC will not clear and return this piece of memory to the OS while the VM is using.
But if you can map some aspects of this VM to Go, perhaps you may have some advantage. For instance, you may map a thread to a goroutine. But a GC need some extra effort. You need to know that there is no references to that portion of memory to clean it. And this is totally specific to the VM