为什么“ gc.get_objects“功能中会导致循环参考或内存泄漏?

发布于 2025-02-11 21:42:18 字数 450 浏览 1 评论 0原文

此代码将成为循环参考!, 如果对象禁用自动垃圾收集,则“ gc.disable()”, 运行它会使内存泄漏!

import gc, sys


def test_func():
    objs = gc.get_objects()
    priint("-----End: test_func %s" % sys.getrefcount(test_func))

test_func()

我知道这是对的,但是为什么???

import gc, sys


def test_func():
    objs = gc.get_objects()
    del objs
    priint("-----End: test_func %s" % sys.getrefcount(test_func))

test_func()

版本:2.7 谢谢兄弟!

this code will make circular reference!,
if object disable automatic garbage collection,"gc.disable()",
running it will make memory leaking!

import gc, sys


def test_func():
    objs = gc.get_objects()
    priint("-----End: test_func %s" % sys.getrefcount(test_func))

test_func()

l know this is right, but why???

import gc, sys


def test_func():
    objs = gc.get_objects()
    del objs
    priint("-----End: test_func %s" % sys.getrefcount(test_func))

test_func()

version: 2.7
thank bro!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一向肩并 2025-02-18 21:42:18

我就知道

case frame in gc.get_objects()


def TestFunc3():
    lst = gc.get_objects()
    print("sys._getframe() in lst: %s" % (sys._getframe() in lst))
    print lst in sys._getframe().f_locals.values()
    
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))
TestFunc3()
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))
TestFunc3()
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))


"""
--TestFunc3 ref: 2
sys._getframe() in lst: True
True
--TestFunc3 ref: 3
sys._getframe() in lst: True
True
--TestFunc3 ref: 4
"""

I knew it

case frame in gc.get_objects()


def TestFunc3():
    lst = gc.get_objects()
    print("sys._getframe() in lst: %s" % (sys._getframe() in lst))
    print lst in sys._getframe().f_locals.values()
    
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))
TestFunc3()
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))
TestFunc3()
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))


"""
--TestFunc3 ref: 2
sys._getframe() in lst: True
True
--TestFunc3 ref: 3
sys._getframe() in lst: True
True
--TestFunc3 ref: 4
"""
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文