asyncio 的 queue.get()问题

2016-01-08 11:25:43 +08:00
 ryanking8215

描述

python3.4 环境
- 任务 1 往 queue 每隔 2s 塞一个数据
- 任务 2 使用一个循环, 1s 超时获取 queue 数据。

现象: 任务 2 一直得不到数据。, 从原则上说,这把 get()超时了,只要 put()过了,下一把 get 怎么也能得到数据。但就是没有数据,一直超时。

任务 2 为什么不一直 yield from queue.get()呢?一直 yield from 当然可以得到,问题就是这个 asyncio.wait_for()超时会得不到, timeout=1 得不到, timeout=0.5 是 ok 的, >2 是 ok 的,=2 也是得不到的。

代码

import asyncio

#from queues import Queue

class Test:
    def __init__(self, loop=None):
        self._queue = asyncio.Queue(loop=loop)
        self._future = asyncio.Future(loop=loop)

    @asyncio.coroutine
    def run(self):
        asyncio.async(self._feed_queue(2))
        asyncio.async(self._recv())

    @asyncio.coroutine
    def _feed_queue(self, interval):
        v = 0
        while True:
            yield from asyncio.sleep(interval)
            print("feed")
            yield from self._queue.put(v)
            v = v+1
            # print("%s" % repr(self._queue))


    @asyncio.coroutine
    def _recv(self):

        while True:
            # print('wait')
            try:
                r = yield from asyncio.wait_for(self._queue.get(), timeout=1.0)
                print(">>>>>>>>>>>>>>>",r)
            except asyncio.TimeoutError:
                print("timeout")
                continue
            except:
                break

        print("quit")


loop = asyncio.get_event_loop()
t = Test(loop=loop)
asyncio.async(t.run())
loop.run_forever()
3140 次点击
所在节点    Python
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/249249

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX