python - for 语句中的动态数组

标签 python c++ django algorithm data-structures

我有一个包含大量记录的数据库和一个使用 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/

相关文章:

python - 无法在 django 1.11 中使用 python 2.7 连接 mysql,同时安装 mysqlclient 和 MySQL-python 时出现错误

python - Gunicorn 未在 AWS EC2 上创建 .sock 文件

c# - 在多线程 C# 应用程序中嵌入 Python

c++ - .h和.cpp文件分离时出错,但仅使用.h文件则没有错误。我究竟做错了什么?

c++ - 使用参数列表中的绝对路径启动 QProcess

c++ - 成员变量不保存从函数成员添加到它的值

Django Rest框架无法处理ModelViewSet中的多个对象

python - 编写 user.get_profile() 自定义函数,如果没有任何身份验证配置文件,应创建该函数

python - 通过 bins 在 Numpy 中的向量上应用函数

python - 更改 wx.Notebook 中选项卡的标题