我在 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/