【问题标题】:Python queue.get(block=true) with timeout does not return when item is added添加项目时,带有超时的 Python queue.get(block=true) 不会返回
【发布时间】:2014-01-18 23:12:35
【问题描述】:

我的 python 应用程序中有 2 个线程。 线程 A(嗯,基本上是“主”线程)被添加到队列中。 线程 B 正在从队列中获取它。

代码 A:

def addTrade(self, date, volume, price, exchange):
    '''
    Adds a single trade to the database
    '''
    print "> ADD"
    try:
        self._incomingDataQueue._put(TradeData(exchange=exchange, date=date, volume=volume, price=price))
        # self._dataAvailableEvent.set()
        # self._dataAvailableEvent.clear()
        print "< ADD"
    except Exception as ex:
        print "ex: %s" % ex

线程 B 有这个:

print "> GET"
t = int(time.time())
tradeData = self._incomingDataQueue.get(block=True, timeout=20)
print "< GET %d " % (int(time.time()) - t)

所以...

发生的事情是这样的: 线程 B 启动并等待队列中的项目(超时 = 20 秒)。几乎在 B 启动后的瞬间,一个项目被添加到队列中。 15 秒后,另一个项目。

但是:队列中的获取仅在 20 秒后返回。当有新数据可用时,我希望它“几乎立即”返回。

输出:

> GET
> ADD
< ADD
> ADD
< ADD
< GET 20

那么,这是队列的正常行为吗?还是应该使用其他机制?

提前致谢!

【问题讨论】:

    标签: python multithreading queue


    【解决方案1】:

    问题是您调用的是Queue._put 而不是Queue.put。我看不出你为什么要这样做。

    前导下划线表示_put方法不是Queue类的公共接口的一部分,所以你不应该直接调用它。

    【讨论】:

    • 你完全正确!这是我的编辑智能感知的,但我不知何故忽略了它!现在可以了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多