我正在阅读 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/