双端队列的线程安全复制,但不阻止附加

问题描述 投票:1回答:1

我正在尝试在python中创建循环缓冲区。我最好的实现方法是使用固定长度的deque。(基本实施)

class RingBuffer(object):
    def __init__(self, size):
        self.mutex = Lock()
        self.deque = collections.deque(maxlen=size)

    def push_elem(self, element):
        copy.deepcopy(element)
        with self.mutex:
            self.deque.append(element)

    def get_data(self, event, callback=None):
        with self.mutex:
            return copy.deepcopy(list(self.deque))


    def get_elem(self):
        if self.deque:
            with self.mutex:
                return cp.deepcopy(self.deque[-1])
        return None

我知道从两侧追加和删除元素都是线程安全的,但我还需要能够复制N个元素。这就是为什么我使用此互斥锁。问题是我不想在其他线程将数据复制到缓冲区时阻止新元素的插入。没有互斥锁是否可以实现此行为?

python multithreading deque
1个回答
0
投票

在CPython中,此副本是原子副本(一旦它开始运行):

s = list(islice(some_deque, 20))

列表构建,使用itertools切片以及双端队列迭代均在C中实现,没有纯python回调。同样,复制操作不会导致任何DECREF降至零,从而消除了另一个非原子行为的来源。

© www.soinside.com 2019 - 2024. All rights reserved.