用glib收集垃圾? [英] Garbage collection with glib?

查看:129
本文介绍了用glib收集垃圾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



glib和gobject使用引用计数(reference count)。

我想将垃圾收集语言(具体来说,它使用古老的Boehm libgc)接口到API的glib系列。在内部管理对象的生存期。包装这些东西的正常方式是使用垃圾收集的对等体对象,该对象持有对glib对象的引用,并在对等体完成时丢弃该引用;这意味着当应用程序使用对等体时,glib对象保持活动状态。我之前完成了这个工作,并且它可以工作,但是它非常痛苦并且有其自身的问题(例如生成同一个基础对象的两个同伴)。



无论如何,我已经获得了垃圾收集器的所有开销 ,理想情况下,我想要做的就是关闭glib的引用计数并为所有内容使用垃圾回收器。这将简化界面,不会结束,并有望提高性能。



面对事情,这看起来相当简单 - 将垃圾收集器终结器连接到glib对象终结者,并且将ref和unref函数覆盖为noops--但是进一步的调查显示除此之外还有更多:例如,glib非常喜欢保留自己的分配器池,当然,我让它做到了垃圾收藏家认为池中的所有东西都是实时的,它会泄露的。

说服glib使用libgc实际上可行吗?如果是这样,我可能会面临哪些其他问题?什么样的glib性能影响会迫使所有的分配都通过libgc产生(而不是使用当前在glib中的优化分配器)?

(glib文档确实表示它应该干净地连接到一个垃圾收集器......)

解决方案

否。



由于询问我发现libgc不搜索由第三方库拥有的内存以供引用。这意味着如果glib在其自己的工作空间中只有通过libgc分配的对象的引用,libgc将收集它,然后程序将崩溃。



libgc是只能安全地用于主程序所拥有的对象。


I would like to interface an garbage collected language (specifically, it's using the venerable Boehm libgc) to the glib family of APIs.

glib and gobject use reference counting internally to manage object lifetime. The normal way to wrap these is to use a garbage collected peer object which holds a reference to the glib object, and which drops the reference when the peer gets finalised; this means that the glib object is kept alive while the application is using the peer. I've done this before, and it works, but it's pretty painful and has its own problems (such as producing two peers of the same underlying object).

Given that I've got all the overhead of a garbage collector anyway, ideally what I'd like to do is to simply turn off glib's reference counting and use the garbage collector for everything. This would simplify the interface no end and hopefully improve performance.

On the face of things this would seem fairly simple --- hook up a garbage collector finaliser to the glib object finaliser, and override the ref and unref functions to be noops --- but further investigation shows there's more to it than that: glib is very fond of keeping its own allocator pools, for example, and of course I let it do that the garbage collector assume that everything in the pool is live and it'll leak.

Is persuading glib to use libgc actually feasible? If so, what other gotchas am I likely to face? What sort of glib performance impact would forcing all allocations to go through libgc produce (as opposed to using the optimised allocators currently in glib)?

(The glib docs do say that it's supposed to interface cleanly to a garbage collector...)

解决方案

No.

Since asking this I have discovered that libgc does not search memory owned by third-party libraries for references. Which means that if glib has, in its own workspace, the only reference to an object allocated via libgc, libgc will collect it and then your program will crash.

libgc is only safe to use on objects owned by the main program.

这篇关于用glib收集垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆