Are locks unnecessary in multi-threaded Python code because of the GIL?

前端 未结 9 1091
遥遥无期
遥遥无期 2020-12-02 08:11

If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all?

9条回答
  •  萌比男神i
    2020-12-02 09:04

    No - the GIL just protects python internals from multiple threads altering their state. This is a very low-level of locking, sufficient only to keep python's own structures in a consistent state. It doesn't cover the application level locking you'll need to do to cover thread safety in your own code.

    The essence of locking is to ensure that a particular block of code is only executed by one thread. The GIL enforces this for blocks the size of a single bytecode, but usually you want the lock to span a larger block of code than this.

提交回复
热议问题