0

I have some hardware devices in my network that I need to read from them data every 100ms and I need some async way to do it and not to wait to each call.

one way to do it is to use threads and other is using asyncio that uses loop.run_executer method(that create thread for each call). In both cases it will be async so I really don't understand what asyncio is giving us that threads are not.

can someone explain what is the advantage of using asyncio and not threads?

For example How can I turn the next code to be asyncio code:

 def _send(self, data):
        """Send data over current socket

        :param data: registers value to write
        :type data: str (Python2) or class bytes (Python3)
        :returns: True if send ok or None if error
        :rtype: bool or None
        """
        # check link
        if self.__sock is None:
            self.__debug_msg('call _send on close socket')
            return None
        # send
        data_l = len(data)
        try:
            send_l = self.__sock.send(data)
        except socket.error:
            send_l = None
        # handle send error
        if (send_l is None) or (send_l != data_l):
            self.__last_error = const.MB_SEND_ERR
            self.__debug_msg('_send error')
            self.close()
            return None
        else:
            return send_l

This code is taken from ModbusClient class

Thanks

user1628688
  • 85
  • 1
  • 1
  • 4
  • Just look at the according APIs a bit to get an overview of what each tool provides. Also, who says asyncio gives us something that threads don't? – Ulrich Eckhardt Nov 23 '20 at 13:17
  • If you are using asyncio *only* to call `run_in_executor`, then asyncio is giving you nothing and you should use `concurrent.futures` directly. Asyncio provides benefits when you use its native APIs for network communication and similar, in which case it doesn't use threads, but multiplexes data sources through an event loop and async callbacks and coroutines - see answers to [this question](https://stackoverflow.com/questions/49005651/how-does-asyncio-actually-work) for details. – user4815162342 Nov 23 '20 at 13:29

1 Answers1

0

I believe that threads uses each one of your computers threads at the same time, which means that rather than being able to read/process the data one at a time, you will be able to do as many threads as your computer has. This means that you are limited by the hardware that you are programming on.

What asyncio allows you to do is to add the processes to a future, so you get the data, but you don't do anything with it. Once amount of time, or a certain number of datapoints are collected, you can process them all at once.

In this situation asyncio would be advantageous because you can add anywhere from 0 to many thousands of tasks to your future and perform them all at once instead.