位于同一地址的Asyncio共享对象不具有相同的值

时间:2018-11-02 21:31:17

标签: python-3.x python-asyncio

好的,所以我创建了一个DataStream对象,该对象只是asyncio.Queue的包装类。我到处都在传递它,并且一切正常,直到以下功能为止。我正在调用sure_future来运行2个无限循环,一个循环将数据复制到一个DataStream对象中,另一个循环将数据发送到websocket。这是该代码:

def start(self):
    # make sure that we set the event loop before we run our async requests
    print("Starting WebsocketProducer on ", self.host, self.port)
    RUNTIME_LOGGER.info(
        "Starting WebsocketProducer on %s:%i", self.host, self.port)
    #Get the event loop and add a task to it.
    asyncio.set_event_loop(self.loop)

  asyncio.get_event_loop().create_task(self._mirror_stream(self.data_stream))
    asyncio.ensure_future(self._serve(self.ssl_context))enter code here

忽略缩进问题,所以不会正确缩进。

这是失败的方法,错误为“任务已销毁,但仍在等待中!”。请记住,如果我未在“ data_stream.get()”中包含这些行,则该函数运行良好。我确保两个位置的对象都具有相同的内存地址和id()的值。如果我打印来自await self.data_stream.get()的数据,我会得到正确的数据。但是在那之后它似乎只是返回并中断。这是代码:

async def _mirror_stream(self):
    while True:
        stream_length = self.data_stream.length
        try:
            if stream_length > 1:
                for _ in range(0, stream_length):
                    data = await self.data_stream.get()
            else:
                data = await self.data_stream.get()
        except Exception as e:
            print(str(e))
        # If the data is null, keep the last known value
        if self._is_json_serializable(data) and data is not None:
            self.payload = json.dumps(data)
        else:
            RUNTIME_LOGGER.warning(
                "Mirroring stream encountered a Null payload in WebsocketProducer!")
        await asyncio.sleep(self.poll_rate)enter code here

1 个答案:

答案 0 :(得分:0)

通过使用常规queue.Queue对象实现我自己的异步队列,此问题已解决。由于某些原因,即使我不是为asyncio.Queue对象等待,我也要“等待” queue.get()才能使应用程序正常工作...不确定为什么会发生这种情况,但是应用程序运行良好,并且仍然就像Queue来自asyncio库一样执行。感谢那些看过的人!