Python3.4 多线程

线程安全和全局解释器锁 Thread State and the Global Interpreter Lock

总结: 通过使用GIL后, Python多线程安全, 并且数据保持同步.

Python解释器不是完全线程安全的. 为了支持多线程Python程序, 使用了全局锁(也叫全局解释器锁或GIL), 当前线程在安全的访问Python对象前必须使用它. 如果没有全局锁, 即使最简单的操作都会在多线程程序中引发问题: 例如, 两个进程同时增加同一对象的引用数, 引用数可能只增加了一次而不是二次.

The Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global lock, called the global interpreter lock or GIL, that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice.

Therefore, the rule exists that only the thread that has acquired the GIL may operate on Python objects or call Python/C API functions. In order to emulate concurrency of execution, the interpreter regularly tries to switch threads (see sys.setswitchinterval()). The lock is also released around potentially blocking I/O operations like reading or writing a file, so that other Python threads can run in the meantime.

原文地址:https://www.cnblogs.com/yaoyu126/p/6164764.html