您应该在API方法内部还是外部获取锁?

时间:2018-07-26 20:38:12

标签: python concurrency thread-safety locking

假设您有一个要在多个线程之间共享的类。 Python示例:

class ConcurrentClass:
    lock = threading.Lock()

    data1 = 1
    data2 = 2

    def modify_values(self, a, b):
        self.data1 = a
        self.data2 = b

是否最好在方法Modify_values()中获取锁?

# class method
def modify_values(self, a, b):
    with self.lock:
        self.data1 = a
        self.data2 = b


# calling code
co = ConcurrentClass()
co.modify_values(1, 2)

还是应该让调用函数的人来处理?

# class method
def modify_values(self, a, b):
    self.data1 = a
    self.data2 = b


# calling code
co = ConcurrentClass()
with co.lock:
    co.modify_values(1, 2)

0 个答案:

没有答案