gpt4 book ai didi

go - 使用 uintptr 作为弱引用是否安全

转载 作者:行者123 更新时间:2023-12-01 21:16:41 29 4
gpt4 key购买 nike

我想在 Go 中实现一个弱引用,以便我可以使用终结器来检测何时不再需要数据结构并能够存储/清理数据。

我发现的一种方法是使用 uintptr 作为映射键,这样当调用终结器时,我可以使用传递给终结器函数的指针值访问/清理数据。这样做安全吗?

我想我的问题是:Go 使用移动垃圾收集器吗?还是会?

最佳答案

The link你自己引用的in a comment提供您要问的问题的答案:不要给客户一个指向您想要大惊小怪的底层对象的指针,而是给他们一个指向包装器对象的指针:

type internal struct {
// all the internal stuff goes here
}

// change the name Wrapper below to something more suitable
type Wrapper struct {
*internal // or p *internal if you want to be overly verbose
}

func NewWhatever(/*args*/) *Wrapper {
p := &Wrapper{...} // fill this part in
runtime.SetFinalizer(p, wrapperGotCollected)
return p
}

func wrapperGotCollected(p *Wrapper) {
// since p itself is about to be collected,
// **p (or *((*p).p)) is no longer accessible by
// the user who called NewWhatever(). Do
// something appropriate here.
}

请注意,这*internal 上使用终结器,而是在*Wrapper 上使用终结器:当时wrapperGotCollected 被调用,*internal 对象本身保证仍然存在,因为 p 本身还没有被 GC-ed(有点像到一半,并且将在 wrapperGotCollected 返回后不久或之后完成剩余的路程。

关于go - 使用 uintptr 作为弱引用是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63025066/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com