V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
sbldehanhan
V2EX  ›  Python

Python 中的列表是线程安全的吗?

  •  
  •   sbldehanhan · 310 天前 · 1541 次点击
    这是一个创建于 310 天前的主题,其中的信息可能已经有所发展或是发生改变。

    既然 Python 有全局锁,只能是单线程。 那我两个线程同时往一个列表里写东西,还需要加锁吗?

    8 条回复    2023-05-25 00:45:49 +08:00
    dbow
        1
    dbow  
       310 天前
    不能保证顺序
    cnuser002
        2
    cnuser002  
       310 天前
    append 可以不加锁。参考 https://docs.python.org/3.5/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe

    GIL 可以保证同一时间只有一个线程在活动,但如果你的操作本身不是原子操作,就是说由几步构成的,那有可能你干到一半就切到另一个线程上了。
    deplivesb
        3
    deplivesb  
       309 天前
    CEBBCAT
        4
    CEBBCAT  
       309 天前
    单核 CPU 就没有并发问题了吗 XD
    sbldehanhan
        5
    sbldehanhan  
    OP
       309 天前
    @cnuser002 明白了,GIL 锁和多线程的锁完全是两码事。多线程的锁在 Python 上也不可少,其他语言多个线程是同时运行,Python 是切换着运行。无论哪种方式,只要涉及到线程切换就需要在临界区加锁。
    sbldehanhan
        6
    sbldehanhan  
    OP
       309 天前
    @CEBBCAT 对。我之前理解错了。
    whoosy
        7
    whoosy  
       309 天前
    GIL 锁的是字节码指令,一行代码有可能涉及到多个字节码指令
    nethard
        8
    nethard  
       309 天前
    在 cpython 里可以认为是安全的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5331 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 08:05 · PVG 16:05 · LAX 01:05 · JFK 04:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.