推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
qybing
V2EX  ›  Python

当使用 Python 多线程创建多个类对象,并传到线程函数里面去,会因为每增加一个线程而创建一个类对象而导致内存增加吗

  •  
  •   qybing · Jul 27, 2020 · 2680 views
    This topic created in 2141 days ago, the information mentioned may be changed or developed.
    15 replies    2020-07-28 16:11:28 +08:00
    imn1
        1
    imn1  
       Jul 27, 2020
    关注一下
    有文章写线程结束未必销毁对象,我不熟,听楼下意见

    我现在喜欢函数+dataclass,或者在一个类方法里面做线程处理,每线程只生成记录数据的对象
    这样不会创建很多对象
    O0oOo0
        2
    O0oOo0  
       Jul 27, 2020
    nthhdy
        3
    nthhdy  
       Jul 27, 2020
    是在线程函数里定义 class,还是预先定义好多个 class 传入线程函数?

    照我的浅见,线程函数不定义新 class,不会有类对象被新建,不会占更多内存。
    如果在线程函数里面定义 class,每一个新进程都会创建自己的类对象,起多少线程就占多少份内存。
    nthhdy
        4
    nthhdy  
       Jul 27, 2020
    @O0oOo0 长知识了

    但是这篇文章里讲的,前提是 fork 子进程且使用到共享内存。跟楼主讲的不一样,楼主都没新建进程,只新建线程了,无所谓写时复制。
    qybing
        5
    qybing  
    OP
       Jul 27, 2020
    @nthhdy 线程外面定义 class,每起一个线程就会定义一个 class,然后往线程函数里面传
    nthhdy
        6
    nthhdy  
       Jul 27, 2020
    照我浅见,如果 python2 的话,我理解类似这样?

    ```python

    import thread

    def thread_func(cls):
    a = cls()
    # do something with a ....

    def work():

    class DefineClass:
    pass
    print id(DefineClass)

    thread.start_new_thread(thread_func, (DefineClass, ))


    for i in range(100):
    work()

    ```

    那么每次调用 work,都会新建一个类对象
    nthhdy
        7
    nthhdy  
       Jul 27, 2020
    https://gist.github.com/workingenius/1a4df7f9ae8f366447f2c6138630c99b

    代码不好看,抱歉。看看这个行不行
    fasionchan
        8
    fasionchan  
       Jul 27, 2020
    内存是否增加取决于对象创建以及销毁,跟多线程无关。如果你一直创建对象,但不回收,内存肯定是要增加的。
    O0oOo0
        9
    O0oOo0  
       Jul 28, 2020
    @nthhdy 感谢指正
    qybing
        10
    qybing  
    OP
       Jul 28, 2020
    @fasionchan 线程函数是死循环,对象不销毁
    qybing
        11
    qybing  
    OP
       Jul 28, 2020
    @nthhdy 你这个类是在函数里面定义的,外面可以调用吗,不太懂 python2
    qybing
        12
    qybing  
    OP
       Jul 28, 2020
    有什么方案可以解决内存增加的问题吗
    fasionchan
        13
    fasionchan  
       Jul 28, 2020
    @qybing 意思是线程不退出吗?
    qybing
        14
    qybing  
    OP
       Jul 28, 2020
    @qybing 对,不会退出,也正在想怎么手动关闭其中一个线程
    nthhdy
        15
    nthhdy  
       Jul 28, 2020
    @qybing 设置个变量让线程里的循环 break 了不就行
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2891 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 12:34 · PVG 20:34 · LAX 05:34 · JFK 08:34
    ♥ Do have faith in what you're doing.