Can you deallocate memory with Go garbage collection disabled?

huangapple go评论91阅读模式
英文:

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&#183;free accessible to your program
using cgo.

Build your own package called, for example, mem and create two files:

mem.go

package mem

import &quot;unsafe&quot;
import &quot;reflect&quot;

func FreePtr(p unsafe.Pointer)

func Free(v interface {}) {
	FreePtr(unsafe.Pointer(reflect.ValueOf(v).Elem().Pointer()))
}

runtime.c

// +build gc
#include &lt;runtime.h&gt;

void &#183;Free(void* foo) {
    runtime&#183;free(foo);
}

Example usage (free a slice and print number of frees):

import &quot;free/mem&quot;

func main() {
	var m1, m2 runtime.MemStats

	runtime.ReadMemStats(&amp;m1)
	c := make([]int, 10000)
	inspect.Free(&amp;c)
	runtime.ReadMemStats(&amp;m2)

	fmt.Printf(&quot;%d vs %d\n&quot;, m1.Frees, m2.Frees)
}

You should see that there was one more free than before.

huangapple
  • 本文由 发表于 2013年11月8日 06:56:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/19848413.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定