由于GIL,在多线程Python代码中是否不需要锁? [英] Are locks unnecessary in multi-threaded Python code because of the GIL?

查看:212
本文介绍了由于GIL,在多线程Python代码中是否不需要锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您依赖具有全局解释器锁(即CPython)的Python实现并编写多线程代码,那么您真的需要锁吗?

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?

如果GIL不允许并行执行多条指令,那么共享数据是否有必要受到保护?

If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect?

很抱歉,如果这是一个愚蠢的问题,但这是我一直想知道的关于多处理器/核心机器上的Python的东西.

sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines.

同样的情况也适用于具有GIL的任何其他语言实现.

same thing would apply to any other language implementation that has a GIL.

推荐答案

如果您在线程之间共享状态,则仍然需要锁. GIL仅在内部保护解释器.您自己的代码中仍然可能会有不一致的更新.

You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code.

例如:

#!/usr/bin/env python
import threading

shared_balance = 0

class Deposit(threading.Thread):
    def run(self):
        for _ in xrange(1000000):
            global shared_balance
            balance = shared_balance
            balance += 100
            shared_balance = balance

class Withdraw(threading.Thread):
    def run(self):
        for _ in xrange(1000000):
            global shared_balance
            balance = shared_balance
            balance -= 100
            shared_balance = balance

threads = [Deposit(), Withdraw()]

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

print shared_balance

在这里,您的代码可能会在读取共享状态(balance = shared_balance)和写回更改的结果(shared_balance = balance)之间中断,从而导致更新丢失.结果是共享状态的随机值.

Here, your code can be interrupted between reading the shared state (balance = shared_balance) and writing the changed result back (shared_balance = balance), causing a lost update. The result is a random value for the shared state.

要使更新一致,运行方法将需要在读取-修改-写入部分(循环内部)周围锁定共享状态,或者具有

To make the updates consistent, run methods would need to lock the shared state around the read-modify-write sections (inside the loops) or have some way to detect when the shared state had changed since it was read.

这篇关于由于GIL,在多线程Python代码中是否不需要锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆