I have been using threading
for years but it came out of fashion, probably for very good reasons. I therefore tried to understand how this thing works.
My solution with threading
Consider the threading
code below:
import threading
import time
def say_wait_10():
print("from say_wait_10 start")
time.sleep(10)
print("from say_wait_10 end")
def say():
print("from say")
threading.Thread(target=say_wait_10).start()
threading.Thread(target=say).start()
The idea is to start a task that takes time (say_wait_10()
), let it run on its own, and in parallel start a short lived one (say()
), that also runs on its own. They are independent, one does not block the other (this may be more or less effective depending on whether the task is CPU or I/O intensive).
The output is, as expected
from say_wait_10 start
from say
from say_wait_10 end
What I tried with asyncio
I now tried to convert that into asyncio
, following the documentation. I came up with
import asyncio
async def say_wait_10():
print("from say_wait_10 start")
await asyncio.sleep(10)
print("from say_wait_10 end")
async def say():
print("from say")
async def main():
await asyncio.create_task(say_wait_10())
await asyncio.create_task(say())
asyncio.run(main())
How I understood the code above is that asyncio.create_task(say_wait_10())
creates a task that immediately starts to run on its own. The await
is the equivalent of threading.Thread.join()
to make sure the main code waits for the coroutine (or task in the example above) has time to finish.
The output is
from say_wait_10 start
from say_wait_10 end
from say
Ah, so the code in the task ran synchronously and only after it was done, say()
was called. Where is the asynch part in this?
I then thought that maybe the await
actually means "to wait" (for the task to finish before going further) so I removed it, but this just started the program, ran whatever was runnable during the time of the execution of the main program and then it was over
from say_wait_10 start
from say
My question
How to replicate my threading
code - I would really appreciate very much an explanation of what is going on in the code so that I can grasp the philosophy of asyncio
before going further.
Alternatively, a pointer to a tutorial that would walk me from threading
to asyncio
would be awesome.
Note
If this can help, I have no problems with the idea of Promises in JS, despite having just a very superficial understanding of JS (that is, more superficial than the one I have in Python - I am just an amateur developer). In JS, due to the place the code runs, I do not have problems to imagine the fact that "things happen when they happen, and then they update some part of the DOM (which is the typical use for me))