Page 1 of 1

_thread Vs uasyncio

Posted: Sat Jan 22, 2022 11:16 pm
by KJM
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?

Re: _thread Vs uasyncio

Posted: Sun Jan 23, 2022 6:04 pm
by pythoncoder
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.