_thread Vs uasyncio

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
KJM
Posts: 158
Joined: Sun Nov 18, 2018 10:53 pm
Location: Sydney AU

_thread Vs uasyncio

Post by KJM » Sat Jan 22, 2022 11:16 pm

What do you think of _thread Vs uasyncio in terms of the user experience? "Why do you ask?" I hear you say

I got sick of waiting around for urequests to give up on bad connections so I tried timing it out by running it as a thread. Instead of

Code: Select all

_request("GET", url)
I did

Code: Select all

def _timeout(method, url):
  response=0; import _thread; _thread.start_new_thread(_request, (method, url))
  for i in range(5):                                                             # 5s timeout for dns+srvr
    if response: return response
    time.sleep(1)
    
_timeout("GET", url)
This worked & the only mod I had to make to _request was to make response a global instead of returning it as previously. Emboldened by this success, I wondered if I might try my luck with uasyncio? Big mistake. First problem, all the online tutorials for uasyncio where way more cerebral than the thread examples. Second, I can't get it to work

Code: Select all

def _timeout(method, url):
  response=0; asyncio.create_task(_request(method, url)); await asyncio.sleep(0)
  for i in range(5):                                                             # 5s timeout for dns+srvr
    if response: return response
    time.sleep(1)
    
_timeout("GET", url)   


>>AttributeError: generator object has no attribute text
I tried moving the class definitions for text, etc inside the asyncio task with the rest of _request but it didn't help. Not only that but the print("_request is running") statement I put at the front of the task never executes so I doubt the _request task has even started. Any thoughts on where I'm going wrong?

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: _thread Vs uasyncio

Post by pythoncoder » Sun Jan 23, 2022 6:04 pm

In general uasyncio has many advantages over threading, detailed here. You might like to watch this video on the use of cooperative multi tasking in web programming.

There is a significant learning curve but it's well worth tackling - uasyncio is very much more efficient on resource-constrained devices.
Peter Hinch
Index to my micropython libraries.

Post Reply