我有一个 ADT(PCB 又名进程控制块),我想将它们放入优先级队列。我该怎么做?

我已经使用 How to put items into priority queues? 设置了第二优先级,以确保队列的正确排序。在这里我可以让PCB具有可比性,但在另一个类中,它可能没有意义?在这种情况下,我该怎么办?

更新

我的代码与发布的 https://stackoverflow.com/a/9289760/292291 非常相似

class PCB:
    ...

# in my class extending `PriorityQueue`
PriorityQueue.put(self, (priority, self.counter, pcb))

我认为问题是pcb在这里仍然没有可比性

最佳答案

好的只是结束这个问题。这是我所做的:

使 ADT 具有可比性:实现 __lt__()

def __lt__(self, other):
    selfPriority = (self.priority, self.pid)
    otherPriority = (other.priority, other.pid)
    return selfPriority < otherPriority

这样,我可以简单地使用 queue.put(obj)
我发现@larsmans 说得对


jiewmeng@JM:~$ python3.2
Python 3.2.2 (default, Sep  5 2011, 21:17:14)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Test:
...     def __init__(self, name):
...             self.name = name
...
>>> from queue import PriorityQueue
>>> q = PriorityQueue()

# duplicate priorities triggering unorderable error
>>> q.put((2, Test("test1")))
>>> q.put((1, Test("test1")))
>>> q.put((3, Test("test1")))
>>> q.put((3, Test("test1")))
>>> q.put((3, Test("test2")))
>>> while not q.empty():
...     print(q.get().name)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib/python3.2/queue.py", line 195, in get
    item = self._get()
  File "/usr/lib/python3.2/queue.py", line 245, in _get
    return heappop(self.queue)
TypeError: unorderable types: Test() < Test()

# unique priority fields thus avoiding the problem
>>> q = PriorityQueue()
>>> q.put((3, Test("test1")))
>>> q.put((5, Test("test5")))

>>> while not q.empty():
...     print(q.get()[1].name)
...
test1
test5

关于python - 我注意到我不能将 PriorityQueue 用于对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9292415/

10-12 13:09