Python 线程锁共享对象无法正常工作

Python threading lock shared object not working properly

我有两个或更多线程实例化自同一个 class,称为 'Player',共享 memory_buffer。

class Player(Thread):
    def __init__(self, player_number, memory_buffer):
        super().__init__()
        self.memory_buffer = memory_buffer
        self.player_number = player_number
        self.lock = Lock()

    def add_data(self, count):
        with self.lock:
            self.memory_buffer.add_data(self.player_number, count)

    def run(self):
        count = 0
        while True:
            self.add_data(count)
            count += 1

其中 memory_buffer 是一个对象,如下所示:

class MemoryBuffer:
    def __init__(self, max_size=int(1e6)):
        self.player_count = np.zeros((max_size, 2)) - 1
        self.ptr = 0


    def add_data(self, player_number, count):
        self.player_count[self.ptr] = [player_number, count]
        self.ptr += 1

然后我开始线程

num_player = 5
memory_buffer = MemoryBuffer(max_size=int(1e6))
players = [Player(player_number=i + 1, memory_buffer=memory_buffer) for i in range(5)]
for p in players:
    p.start()

我在 memory_buffer 中设置数据时发现一个问题,有时玩家线程提供的数据会覆盖 memory_buffer 中的 player_count。

例如, 当玩家 1 已经达到 1000 memory_buffer.player_count 时,我必须具有从 0 到 999 的此类值,尽管序列被其他玩家线程中断。但是有些值丢失了,我打印了日志,然后我看到一些线程有时会在 memory_buffer.ptr 位置被覆盖。 示例如下

Memory buffer data that is produced by player 1: [[1, 0], [1, 1], [1, 2], ... , [1, 999]] 
Missing buffer data: [[1, 7], [1, 157]]

似乎锁无法正常工作。有人可以帮助我正确工作吗?

目前锁在 Player class 中管理,这意味着每个玩家初始化并使用不同的 Lock 对象,您应该将锁检查移至 MemoryBuffer class 它将由 add_data 函数本身管理