我有一个包含大量记录的数据库和一个使用 Django 框架的代码。现在我对该数据库运行查询并将结果收集在列表中。每条记录都有一个名为priority 的字段,然后使用for 语句根据该优先级逐一处理它们。但我有一个问题。
我的数据库是非常动态的,当我处理当前列表时,我可能在数据库中有一个具有更高优先级的新记录!我必须先处理它,但它是当前的体系结构,我不能,我必须等待终止当前的列表进程。我怎样才能实现我的目标?
我有一个替代方法,但我不确定这是最好的方法。在 while 语句中,我可以对数据库运行查询并仅获取一条具有更高优先级的记录。
您对我的替代解决方案有何看法?有没有更好的办法?
最佳答案
如 WhozCraig 所述,您可以使用 treading 获取使用 Queue 处理或子处理高优先级数据的线程。 下面是它的外观示例。如果你想使用多个线程和更多的函数,而不是只使用 run() 你将不得不重新定义从 thread1_high_priority = High_priority_Thread(1, 10, queue)# 调用的线程对象,其中参数在 run() 中定义为 thread1_high_priority = High_priority_Thread(target= functionname, name = name)# 和init一样,def init (self, target, name):.
import Queue
import threading
import time
queue = Queue.Queue()
class High_priority_first(threading.Thread):
""" a threading class"""
def __init__ (self, start, stop, queue):
self.start = start
self.stop = stop
self.queue = queue
threading.Thread.__init__(self)
# Write a function, run(), that counts the higher priority data and extend it to
# also count lower priority, or create another function for low priority data and
# run them with a separate thread than thread 1.
def run(self):
while True:
if self.start != stop:
self.start += 1
self.queue.put(self.start)
else:
break
thread1_high_priority = High_priority_Thread(1, 10, queue)# start at 1 and stop at 10
thread1_high_priority.start() #start thread1
thread2_lower_priority = High_priority_Thread(1, 3, queue)# start at 1 and stop at 3
thread2_lower_priority.start() #start thread2
while True:
if queue != None: # check that queue isn't empty
out = queue.get()
print out
else:
break
关于python - for 语句中的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21721064/