Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #86156

Re: Question on asyncio

From Marko Rauhamaa <marko@pacujo.net>
Newsgroups comp.lang.python
Subject Re: Question on asyncio
Date 2015-02-22 23:21 +0200
Organization A noiseless patient Spider
Message-ID <8761atiqvt.fsf@elektro.pacujo.net> (permalink)
References <52b94569-1480-4a05-a58f-13c2cb19229a@googlegroups.com>

Show all headers | View raw


pfranken85@gmail.com:

> I have some functions which are reading values from hardware. If one
> of the values changes, I want a corresponding notification to the
> connected clients. The network part shouldn't be the problem. Here is
> what I got so far:
>
> @asyncio.coroutine
> def check():
>   old_val = read_value_from_device()
>   yield from asyncio.sleep(2)
>   new_val = read_value_from_device()
>   # we may have fluctuations, so we introduce a threshold
>   if abs(new_val-old_val) > 0.05:
>       return new_val
>   else:
>       return None
>       
> @asyncio.coroutine
> def runner():
>   while 1:
>     new = yield from check()
>     print(new)

In asyncio, you typically ignore the value returned by yield. While
generators use yield to communicate results to the calling program,
coroutines use yield only as a "trick" to implement cooperative
multitasking and an illusion of multithreading.

Thus, "yield from" in asyncio should be read, "this is a blocking
state."

> Is this the way one would accomplish this task? Or are there better
> ways? Should read_value_from_device() be a @coroutine as well? It may
> contain parts that take a while ... Of course, instead of print(new) I
> would add the corresponding calls for notifying the client about the
> update.

How do you read a value from the hardware? Do you use a C extension? Do
you want read_value_from_device() to block until the hardware has the
value available or is the value always available for instantaneous
reading?

If the value is available instantaneously, you don't need to turn it
into a coroutine. However, if blocking is involved, you definitely
should do that. Depending on your hardware API it can be easy or
difficult. If you are running CPython over linux, hardware access
probably is abstracted over a file descriptor and a coroutine interface
would be simple.


Marko

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Question on asyncio pfranken85@gmail.com - 2015-02-22 09:47 -0800
  Re: Question on asyncio Marko Rauhamaa <marko@pacujo.net> - 2015-02-22 23:21 +0200
    Re: Question on asyncio pfranken85@gmail.com - 2015-02-23 01:48 -0800
      Re: Question on asyncio Marko Rauhamaa <marko@pacujo.net> - 2015-02-23 15:27 +0200
        Re: Question on asyncio Jonas Wielicki <jonas@wielicki.name> - 2015-02-23 16:05 +0100
          Re: Question on asyncio Marko Rauhamaa <marko@pacujo.net> - 2015-02-23 18:30 +0200

csiph-web