I want to use async in python like c# or javascript.For example I want my program not to block next codes or maybe buttons in app while sending a request.I wrote some code about that.However I dont know whether this usage is true or false.I can't understand asyncio
import asyncio
import threading
import time
async def waitForMe(name):
for i in range(5):
await asyncio.sleep(1)
print(name)
async def main():
task1 = asyncio.create_task(waitForMe("task1"))
task2 = asyncio.create_task(waitForMe("task2"))
task3 = asyncio.create_task(waitForMe("task3"))
await task1
await task2
await task3
def mfunction():
asyncio.run(main())
t1=threading.Thread(target=mfunction)
t1.start()
for i in range(3):
time.sleep(1)
print("main")
I'd really recommend this excellent asyncio walkthrough, which should answer most of your questions.
A quote from the mentioned article in the light of your code:
[...] async IO is a single-threaded, single-process design: it uses cooperative multitasking, a term that [...] gives a feeling of concurrency despite using a single thread in a single process.
If you don't want your program to block while processing (IO) requests (as stated in your question), concurrency is sufficient (and you don't need (multi)threading)!
Concurrency [...] suggests that multiple tasks have the ability to run in an overlapping manner.
I'll repeat the exact example from the mentioned article, which has a similar structure as your example:
#!/usr/bin/env python3
# countasync.py
import asyncio
async def count():
print("One")
await asyncio.sleep(1)
print("Two")
async def main():
await asyncio.gather(count(), count(), count())
if __name__ == "__main__":
import time
s = time.perf_counter()
asyncio.run(main())
elapsed = time.perf_counter() - s
print(f"{__file__} executed in {elapsed:0.2f} seconds.")
This runs as follows:
$ python3 countasync.py
One
One
One
Two
Two
Two
countasync.py executed in 1.01 seconds.
Note that this examples uses asyncio.gather
to kick-off the three count()
processes in a non-blocking manner. Putting three await count()
statements after one another won't work.
As far as I can see, this is exactly what you are looking for. As demonstrated, you don't need threading
to achieve this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.