简体   繁体   English

Asyncio Python : 对生产者使用无限循环,让消费者在生产者等待 TCP 流时进行处理

[英]Asyncio Python : Using an infinite loop for producer, and let the consumers process when producer is waiting TCP stream

It is the first time that I post here so sorry if everything is not perfect.这是我第一次在这里发帖,如果一切不完美,请见谅。

The situation is the following : I send some bursts of NMEA sentences from a client to a server over a TCP connection using socket in python.情况如下:我使用 python 中的套接字通过 TCP 连接将一些 NMEA 语句从客户端发送到服务器。

I want to avoid any latency for sending and receiving NMEA sentences.我想避免发送和接收 NMEA 语句的任何延迟。 Therefore, I want the receiving of NMEA sentences from the server side to be the priority, and use the time between the bursts of data to process the sentences and store it in a database.因此,我希望以从服务器端接收NMEA语句为优先,利用突发数据之间的时间来处理语句并将其存储在数据库中。

Therefore I wanted to use asyncio (python 3.8) to continuously add the NMEA sentences to a asyncio.queue and let the process of these sentences to happen while the function to receive data from the socket is waiting for new data.因此,我想使用 asyncio (python 3.8) 不断地将 NMEA 语句添加到 asyncio.queue 中,并让这些语句的处理发生,同时从套接字接收数据的函数正在等待新数据。

The pseudo-code of my main loop inside my class is the following :我的类中主循环的伪代码如下:

    #Producer
    async def _read_comms(self,queue):
        """ """
        while True:
            comm_nmea = await self.DataPort.receive_line_async()
            await queue.put(comm_nmea)

    #Consumers
    async def _process_comms(self,queue):
        """ """
        while True:
            comm_nmea = await queue.get()
            data = await self.Parser.parse_comm_nmea(comm_nmea=comm_nmea)
            await self._data_to_db(data)

    #main
    async def receive(self):
        """ """
        self.Logger.info("Start collecting")
        while(True):
            queue = asyncio.Queue()
            await self._read_comms(queue)
            await self._process_comms(queue)
            if self.update_rate != 0:
                time.sleep(self.update_rate)

I must say that I am really new to asyncio (I started for this project).我必须说我对 asyncio 真的很陌生(我开始做这个项目)。 And I am pretty sure that I do a lot of stupid stuff there.而且我很确定我在那里做了很多愚蠢的事情。

The problem with this code, is that I never get outside of the first loop in process_comms().这段代码的问题在于,我永远不会超出 process_comms() 中的第一个循环。 Which was to be expected but I am looking for an solution for what I am trying to do here.这是意料之中的,但我正在为我在这里尝试做的事情寻找解决方案。

Which is as a summary to have two concurrent loop that use the Queue as a buffer.这是具有两个使用队列作为缓冲区的并发循环的总结。 One to feed the queue, the other one to process it.一个用于填充队列,另一个用于处理它。

Never mind, solved my problem !没关系,解决了我的问题!

For those that might encounter same problem :对于那些可能遇到同样问题的人:

I solved that by using :我通过使用解决了这个问题:

queue = asyncio.Queue()
await asyncio.gather(self._read_comms(queue),self._process_comms(queue))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM