Python3.4 多线程

本文探讨了Python全局解释器锁(GIL)的作用及其如何确保多线程程序中的线程安全。介绍了GIL的存在原因及其实现机制,解释了在多线程环境下GIL如何防止数据竞争和保持数据一致性。
线程安全和全局解释器锁 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值