【问题标题】:Using RLock inside shared object在共享对象中使用 RLock
【发布时间】:2015-07-12 11:14:05
【问题描述】:

我有两个线程,每个线程都需要访问一些共享对象。为了保护这个对象的数据,我这样定义它:

class ShareObject:
    def __init__(self):
        self.mutex = threading.RLock()
        self.data = None

    def get(self):
        self.mutex.acquire()
        result = self.data
        self.mutex.release()
        return result

    def set(self, data):
        self.mutex.acquire()
        self.data = data
        self.mutex.release()

这是使用互斥锁保护共享数据的正确方法吗?

【问题讨论】:

    标签: python multithreading thread-safety mutex


    【解决方案1】:

    我认为这是保护数据的正确方法。每一种更高级的风格都和你写的一样。

    我会怎么写,它的作用相同,但更短:

    class ShareObject:
        def __init__(self):
            self.mutex = threading.Lock()
            self.data = None
    
        def get(self):
            with self.mutex: # with unlocks the mutex even if there is an error or return
                return self.data
    
        def set(self, data):
            with self.mutex:
                self.data = data
    
        # more methods
    

    如果 getset 是该类仅有的方法并且没有人使用 mutex 属性,您也可以这样写:

    class ShareObject:
        def __init__(self):
            self.data = None
    
        def get(self):
            return self.data
    
        def set(self, data):
            self.data = data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2011-01-16
      • 1970-01-01
      相关资源
      最近更新 更多