推荐学习书目
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
glacer
0.02D
V2EX  ›  Python

python 中将一个对象作为参数传入多个线程函数中会怎么样?

  •  
  •   glacer · Apr 15, 2016 · 4752 views
    This topic created in 3709 days ago, the information mentioned may be changed or developed.
    这是对象是作为引用传入还是在每个线程中都有复制呢?如果是引用的话,多线程调用对象内部的方法时会影响返回值吗?
    billgreen1
        1
    billgreen1  
       Apr 15, 2016
    先说结论:
    多线程的话,不会。由于 GIL ,不会出现多个线程『同时』修改你的对象。
    多进程,会。因为是 fork 一份数据过去的。


    代码如下,如果多进程,去掉 backend 参数即可。

    from joblib import Parallel, delayed
    import numpy as np
    import time
    class C(object):
    pass

    def func(c):
    c.value+=1
    print(c.value)

    c = C()
    c.value=0

    Parallel(n_jobs=4, backend='threading')(delayed(func)(c) for _ in range(20))
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3299 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 11:13 · PVG 19:13 · LAX 04:13 · JFK 07:13
    ♥ Do have faith in what you're doing.