Python实例变量是线程安全的吗? [英] Are Python instance variables thread-safe?

查看:291
本文介绍了Python实例变量是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,请先检查以下代码:

OK, check following codes first:

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()来锁定此资源,还有更​​好的主意吗?

I'm facing same situation as above. I really want to know if it's thread-safe for self.Counter, well if not, what options do I have? I can only think of threading.RLock() to lock this resource, any better idea?

推荐答案

您可以使用锁,RLock,信号量,条件,事件和队列.
这篇文章对我有很大帮助.
检查一下: Laurent Luce的博客

You can use Locks, RLocks, Semaphores, Conditions, Events and Queues.
And this article helped me a lot.
Check it out: Laurent Luce's Blog

这篇关于Python实例变量是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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