假设您有一个要在多个线程之间共享的类。 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)