【问题标题】:Dynamic array inside a for statementfor 语句中的动态数组
【发布时间】:2014-02-12 07:12:52
【问题描述】:

我有一个包含大量记录的数据库和一个带有 Django 框架的代码。现在我对该数据库运行查询并将结果收集到一个列表中。每条记录都有一个名为 priority 的字段,然后使用 for 语句根据该优先级逐个处理它们。但我有一个问题。

我的数据库是非常动态的,当我处理当前列表时,我可能会在数据库中拥有更高优先级的新记录!我必须先处理它,但它是当前架构,我不能,我必须等待终止当前列表进程。我怎样才能实现我的目标?

我有另一种方法,但我不确定这是最好的方法。在 while 语句中,我可以对数据库运行查询并仅获取一条具有更高优先级的记录。

您对我的替代解决方案有何看法?有没有更好的办法?

【问题讨论】:

  • 不完全确定您打算如何从先前的查询中检测实时行集上的数据库更新,但这可能只是 django 的事情,超出了我的控制范围。我的驾驶室里是这样的:std::priority_queue 和一个组合使用的有序查询。

标签: python c++ django algorithm data-structures


【解决方案1】:

正如 WhozCraig 所说,您可以使用 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

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2020-09-27
    相关资源
    最近更新 更多