python - 正在修改python线程安全中的类变量吗?

标签 python multithreading

我正在阅读 this question (您不必阅读,因为我会复制那里的内容...我只是想向您展示我的灵感)...

所以,如果我有一个计算创建了多少实例的类:

class Foo(object):
  instance_count = 0
  def __init__(self):
    Foo.instance_count += 1

我的问题是,如果我在多个线程中创建 Foo 对象,instance_count 是否正确?从多个线程修改类变量是否安全?

最佳答案

即使在 CPython 上它也不是线程安全的。试试这个自己看看:

import threading

class Foo(object):
    instance_count = 0

def inc_by(n):
    for i in xrange(n):
        Foo.instance_count += 1

threads = [threading.Thread(target=inc_by, args=(100000,)) for thread_nr in xrange(100)]
for thread in threads: thread.start()
for thread in threads: thread.join()

print(Foo.instance_count) # Expected 10M for threadsafe ops, I get around 5M

原因是虽然 INPLACE_ADD 在 GIL 下是原子的,但属性仍然被加载和存储(参见 dis.dis(Foo.__init__))。使用锁来序列化对类变量的访问:

Foo.lock = threading.Lock()

def interlocked_inc(n):
    for i in xrange(n):
        with Foo.lock:
            Foo.instance_count += 1

threads = [threading.Thread(target=interlocked_inc, args=(100000,)) for thread_nr in xrange(100)]
for thread in threads: thread.start()
for thread in threads: thread.join()

print(Foo.instance_count)

关于python - 正在修改python线程安全中的类变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1072821/

相关文章:

python - python的直方图均衡化

python - 用 pyparsing 编写递归解析器

c - 多线程启动安排

c++ - 如何在互斥锁中优先考虑特权线程?

python - Keras/HDF5 类型错误 : PointSelection __getitem__ only works with bool arrays

python - TensorFlow 对象检测 API 中用于平衡数据的类权重

python - 我无法从公共(public)跟踪器 libtorrent 下载 torrent

Java 线程处理

multithreading - C++ 11线程没有匹配的函数调用

c# - 通过单独的线程在表单上绘制