gpt4 book ai didi

python - Python 实例变量是线程安全的吗?

转载 作者:IT老高 更新时间:2023-10-28 20:49:19 25 4
gpt4 key购买 nike

好的,先检查以下代码:

class DemoClass():

def __init__(self):
#### I really want to know if self.Counter is thread-safe.
self.Counter = 0

def Increase(self):
self.Counter = self.Counter + 1

def Decrease(self):
self.Counter = self.Counter - 1

def DoThis(self):
while True:
Do something

if A happens:
self.Increase()
else:
self.Decrease()

time.sleep(randomSecs)

def DoThat(self):
while True:
Do other things

if B happens:
self.Increase()
else:
self.Decrease()

time.sleep(randomSecs)

def ThreadSafeOrNot(self):
InterestingThreadA = threading.Thread(target = self.DoThis, args = ())
InterestingThreadA.start()

InterestingThreadB = threading.Thread(target = self.DoThat, args = ())
InterestingThreadB.start()

我面临与上述相同的情况。我真的很想知道 self.Counter 是否是线程安全的,如果不是,我有什么选择?我只能想 threading.RLock() 来锁定这个资源,有更好的主意吗?

最佳答案

您可以使用锁、RLock、信号量、条件、事件和队列。
这篇文章对我的帮助很多
查看:Laurent Luce's Blog

关于python - Python 实例变量是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com