推荐学习书目
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 · May 24, 2023 · 2594 views
    This topic created in 1093 days ago, the information mentioned may be changed or developed.

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

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

    GIL 可以保证同一时间只有一个线程在活动,但如果你的操作本身不是原子操作,就是说由几步构成的,那有可能你干到一半就切到另一个线程上了。
    deplivesb
        3
    deplivesb  
       May 24, 2023
    CEBBCAT
        4
    CEBBCAT  
       May 24, 2023
    单核 CPU 就没有并发问题了吗 XD
    sbldehanhan
        5
    sbldehanhan  
    OP
       May 24, 2023
    @cnuser002 明白了,GIL 锁和多线程的锁完全是两码事。多线程的锁在 Python 上也不可少,其他语言多个线程是同时运行,Python 是切换着运行。无论哪种方式,只要涉及到线程切换就需要在临界区加锁。
    sbldehanhan
        6
    sbldehanhan  
    OP
       May 24, 2023
    @CEBBCAT 对。我之前理解错了。
    whoosy
        7
    whoosy  
       May 24, 2023
    GIL 锁的是字节码指令,一行代码有可能涉及到多个字节码指令
    nethard
        8
    nethard  
       May 25, 2023
    在 cpython 里可以认为是安全的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   940 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 57ms · UTC 20:24 · PVG 04:24 · LAX 13:24 · JFK 16:24
    ♥ Do have faith in what you're doing.