简体   繁体   English

是否可以仅为程序的一部分使用Boehm垃圾收集器?

[英]Is it possible to use Boehm garbage collector only for the part of the program?

I've read article in LinuxJournal about Boehm-Demers-Weiser garbage collector library . 在LinuxJournal上读过有关Boehm-Demers-Weiser垃圾收集器库的文章 I'm interesting to use it in my library instead of my own reference counting implementation. 我很有兴趣在我的库中使用它而不是我自己的引用计数实现。

I have only one question: is it possible to use gc only for my shared library and still use malloc/free in the main application? 我只有一个问题:是否可以仅将gc用于我的共享库,并且仍然在主应用程序中使用malloc / free? I'm not quite understand how gc checks the heap so I'm worrying about performance of gc in that case and possible side effects. 我不太明白gc如何检查堆,所以我担心在这种情况下gc的性能和可能的副作用。

The example in the manual states: 手册中的示例说明:

It is usually best not to mix garbage-collected allocation with the system malloc - free . 通常最好不要将垃圾收集分配与系统malloc - free If you do, you need to be careful not to store pointers to the garbage-collected heap in memory allocated with the system malloc . 如果这样做,则需要注意不要在使用系统malloc分配的内存中存储指向垃圾收集堆的指针。

And more specifically for C++: 更具体地说是C ++:

In the case of C++, you need to be especially careful not to store pointers to the garbage-collected heap in areas that are not traced by the collector. 对于C ++,您需要特别注意不要在收集器未跟踪的区域中存储指向垃圾收集堆的指针。 The collector includes some alternate interfaces to make that easier. 收集器包含一些备用接口,以使其更容易。

Looking at the source code in the manual you will see the garbage-collected memory is handled through specific calls, hence, the management is handled separately (either by the collector or manually). 查看手册中的源代码,您将看到通过特定调用处理垃圾收集的内存,因此,管理将单独处理(由收集器或手动)。 So as long your library handles its internals properly and doesn't expose collected memory, you should be fine. 因此,只要您的库正确处理其内部并且不暴露收集的内存,您应该没问题。 You don't know how other libraries manage their memory and you can use them as well, don't you? 你不知道其他图书馆如何管理你的记忆,你也可以使用它们,不是吗? :) :)

I believe that yes, you can mix the two: however if you allocate an object with the normal allocator that holds a reference to an object you allocate with the garbage collecting one, then that reference will not be visible to the GC so that object may be prematurely deallocated. 我相信是的,您可以将两者混合使用: 但是如果您使用普通分配器分配一个对象,该对象保存对您使用垃圾收集器分配的对象的引用,那么该引用将不会对GC可见,因此该对象可能过早解除分配。

Have a look at the GC_MALLOC_UNCOLLECTABLE function specification if you need the GC to take account of references in memory that shouldn't be collected. 如果您需要GC考虑不应收集的内存中的引用,请查看GC_MALLOC_UNCOLLECTABLE函数规范。

In summary, yes, but here be dragons if you aren't careful! 总而言之,是的,但如果你不小心, 这里就是龙

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM