英文:
Can you deallocate memory with Go garbage collection disabled?
问题
http://golang.org/ref/spec#Allocation
有一种方法可以分配内存,但我没有看到一种方法可以释放内存(在没有打开Go GC的情况下)。
如果我想使用Go编写一个操作系统,我需要编写一个低级别的Go GC或者禁用Go GC。在后一种情况下,我如何释放内存?
PS - 这个话题在Go邮件列表上已经被广泛讨论过,但我想在这里提出这个具体的问题。
英文:
http://golang.org/ref/spec#Allocation
There is a way to allocate memory, but I don't see a way to deallocate memory (without the Go GC turned on).
If I wanted to write an OS using Go, I would need to either write a low level GC for Go or disable the Go GC. In the latter case, how could I free memory?
PS - this topic has been talked about extensively on the Go mailing list, but I wanted to pose this specific question to SO.
答案1
得分: 7
你可以通过使用cgo,使runtime·free
在你的程序中可访问,从而释放任意内存。
创建一个名为mem
的自定义包,包含两个文件:
mem.go
package mem
import "unsafe"
import "reflect"
func FreePtr(p unsafe.Pointer)
func Free(v interface {}) {
FreePtr(unsafe.Pointer(reflect.ValueOf(v).Elem().Pointer()))
}
runtime.c
// +build gc
#include <runtime.h>
void ·Free(void* foo) {
runtime·free(foo);
}
示例用法(释放一个切片并打印释放的次数):
import "free/mem"
func main() {
var m1, m2 runtime.MemStats
runtime.ReadMemStats(&m1)
c := make([]int, 10000)
mem.Free(&c)
runtime.ReadMemStats(&m2)
fmt.Printf("%d vs %d\n", m1.Frees, m2.Frees)
}
你应该会看到比之前多了一个释放操作。
英文:
You can free arbitrary memory by making runtime·free
accessible to your program
using cgo.
Build your own package called, for example, mem
and create two files:
mem.go
package mem
import "unsafe"
import "reflect"
func FreePtr(p unsafe.Pointer)
func Free(v interface {}) {
FreePtr(unsafe.Pointer(reflect.ValueOf(v).Elem().Pointer()))
}
runtime.c
// +build gc
#include <runtime.h>
void ·Free(void* foo) {
runtime·free(foo);
}
Example usage (free a slice and print number of frees):
import "free/mem"
func main() {
var m1, m2 runtime.MemStats
runtime.ReadMemStats(&m1)
c := make([]int, 10000)
inspect.Free(&c)
runtime.ReadMemStats(&m2)
fmt.Printf("%d vs %d\n", m1.Frees, m2.Frees)
}
You should see that there was one more free than before.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论