|
|
1
23
即使在塞顿也不是螺纹安全。自己试试看:
原因是,虽然inplace_add在gil下是原子的,但属性仍然被加载和存储(请参见 dis.dis(foo.\uuu init\uuuuu) )使用锁序列化对类变量的访问:
|
|
|
2
8
不,它不是线程安全的。几天前我也遇到过类似的问题,多亏了一个装饰师,我选择了实现锁。其好处是它使代码可读: def threadsafe_function(fn):
"""decorator making sure that the decorated function is thread safe"""
lock = threading.Lock()
def new(*args, **kwargs):
lock.acquire()
try:
r = fn(*args, **kwargs)
except Exception as e:
raise e
finally:
lock.release()
return r
return new
class X:
var = 0
@threadsafe_function
def inc_var(self):
X.var += 1
return X.var
|
|
|
3
-4
我会说它是线程安全的,至少在cpython实现上是如此。gil将使您的所有“线程”按顺序运行,这样它们就不会干扰您的引用计数。 |
|
|
user107586 · 如何处理等待句柄不会导致无限循环? 1 年前 |
|
|
ron burgundy · 获取-释放语义是否跨线程传递?[副本] 1 年前 |
|
|
BenjiFB · C#内存缓存:在一次操作中追加到列表? 1 年前 |
|
|
András Takács · Python多线程问题 2 年前 |
|
|
András Takács · Python多线程错误 2 年前 |