【问题标题】:Working of Cache-mem using Queue in Python在 Python 中使用 Queue 处理 Cache-mem
【发布时间】:2016-09-29 05:57:08
【问题描述】:

我已经编写了代码来模拟高速缓存的工作。

在这个模型中,我尝试实现 FIFO 算法,它允许我们删除最后一个未使用的元素(数据、值等)。

我写了一个特殊的函数,它给了我一个带有数字的列表o(这些数字是内存中的地址)。

q=Queue.Queue(800)# Cache - memory. This is a queue which is more likely help me to simulate FIFO-algorithm
QW=[] # External memory
l=raw_input("Enter a desire operation:")#I enter my operation.
for i in range(len(o)):
    time.sleep(0.4)
    u = time.time()
    k=o.pop(0) #o - is the list with numbers (these numbers are addresses in memory). Here I get each address through pop.
    while l=='read': #If operation is "read" then i need to get my adress from q (cache-mem) or from QW (Is the external memory) and put it in q - (is the Cache-memory).
        if k not in q:
            if j in QW and k==j:
                q.put(j)
        else:
            q.get(k)
    while l=='record':#If operation is "record" then i need to write (append to QW) an address in QW or q, but only if the same address have existed already in QW or q.
        if k not in q:
            QW.append(k)
            print QW
        else:
            q.put(k)
    print q.get()

但我得到了错误:

TypeError: argument of type 'instance' is not iterable at line
  if k not in q

【问题讨论】:

  • Queue.Queue 是从哪里来的?它来自某个 3rd 方库吗?
  • 嗨,Alex,更正:您可以使用 if k not in q.queue,但请参阅 this 了解问题和线程安全

标签: python list caching queue


【解决方案1】:

我认为你不能使用队列来做到这一点,而是使用几乎相似的 collections.dequeue,而集合具有快速 append()、pop()。您可以将代码第一行更改为q=collections.deque([],800),并使用q.append,q.popleft()代替q.put,q.get。

【讨论】:

  • 拉克什,谢谢!但是什么 q.popleft()。确实做?它删除并读取还是只读?
  • 我试图更改 q= 所在的行,但出现错误 NameError: name 'collections' is not defined
  • 你必须先通过执行import collections语句来导入模块。
  • 这个函数 q.popleft() 做了两个操作:删除和返回,虽然我只需要返回。有人知道队列中的这个函数吗
  • collections.queue 不是我需要的,因为它会删除数量较少的元素,对吧?我会为每个元素指定添加时间。需要按时间顺序删除元素
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
相关资源
最近更新 更多