python - 在 python 中处理不断变化的列表的正确方法

标签 python multithreading list queue locking

我在 python 中有一个列表,我总是查看它的第一个元素,对其进行一些处理,然后删除该第一个元素。

但是,与此同时,新元素可以同时插入到这个列表中。它们也可以插入到 [0] 位置,如下例所示:

import threading
import time

class listener:

    def __init__(self):

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True
        thread.start()

    def run(self):

        while True:

            if time.monotonic() >= Car.cars_list[0].time:
                # other stuff happens to the 0th element
                # what happens if a new element is insrted just now in car_list?
                Cars.cars_list.pop(0)


class Car:
    # list that is always sorted according to car time parameter
    cars_list = []

    def __init__(self, id, model, time):

        self.id = id

        self.model = model

        self.time = time

        # method that inserts the car to cars_list based on time with simple binary search
        Car.insert(self, Carr.cars_list)

    @staticmethod
    def insert(x, a):
        lo = 0
        hi = len(a)

        while lo < hi:

            mid = (lo + hi) // 2

            if x.time < a[mid].time:

                hi = mid

            else:

                lo = mid + 1

        a.insert(lo, x) 

如果在监听器在当前第 0 个元素上执行某些操作时将一辆新车插入到第 0 个元素中,会发生什么情况。

在我看来,当我在 while True 循环(包括 pop(0) 行)内处理 cars_list 时,我需要锁定 cars_list 以免被更改。

或者可能使用某种类型的缓冲区/队列。有什么建议吗?

最佳答案

如果您需要(如您的示例中所示)检查第一个元素,然后也许删除它(并进行进一步处理),您应该锁定检查和(潜在的)删除,但您可以在处理期间释放锁定(不涉及容器)。

如果总是删除第一个元素,则 list.pop 在 Python 中已经是原子了。 (当然,如果列表可能为(或变为)空,则可能会抛出异常。)

另请注意,从列表的末尾删除比从开头删除要快得多。

关于python - 在 python 中处理不断变化的列表的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53898579/

相关文章:

python - 循环遍历 python 中的文件夹并打开文件会引发错误

python - Pandas groupby 查找两个日期时间列之间的差异

Java:将 double 组添加到列表中

java - 将队列转换为长数组?

python - 是否可以在没有双重拆分的情况下从未解析的字符串列表构造字典理解?

java - JPL 库在多线程程序中的意外行为(Java 和 Prolog 的接口(interface))

java - 在 EJB 程序中使用并发集合

java - 基于数据库更新和时间间隔触发 Java 程序

c# - 使用 LINQ 从字符串列表中提取整数

python - 是否可以同时运行两个版本的 Python?