Difference between revisions of "Asyncio python"

From Teknologisk videncenter
Jump to: navigation, search
(Created page with " =Links= *[https://realpython.com/async-io-python/ Async IO in Python] *[https://realpython.com/python-gil/ The Python GIL - Global Interpreter Lock] Category:Python")
 
m
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
For a primer see [[Yield python]]
  
 +
await vs. asyncio.create()
  
 +
<source lang=python>
 +
import asyncio
 +
import time
 +
 +
async def fetch_data(url):
 +
    # Simulate a long-running network request
 +
    await asyncio.sleep(2)  # Wait for 2 seconds
 +
    print(f"Data fetched from {url}")
 +
 +
async def main():
 +
    task1 = asyncio.create_task(fetch_data("https://example.com"))
 +
    task2 = asyncio.create_task(fetch_data("https://another.example.com"))
 +
 +
    await task1
 +
    await task2
 +
 +
if __name__ == "__main__":
 +
    asyncio.run(main())
 +
</source>
 
=Links=
 
=Links=
 
*[https://realpython.com/async-io-python/ Async IO in Python]
 
*[https://realpython.com/async-io-python/ Async IO in Python]
 
*[https://realpython.com/python-gil/ The Python GIL - Global Interpreter Lock]
 
*[https://realpython.com/python-gil/ The Python GIL - Global Interpreter Lock]
 +
*[https://realpython.com/python-concurrency/ Speed Up Your Python Program With Concurrency]]
  
 
[[Category:Python]]
 
[[Category:Python]]

Latest revision as of 09:03, 5 October 2024

For a primer see Yield python

await vs. asyncio.create()

import asyncio
import time

async def fetch_data(url):
    # Simulate a long-running network request
    await asyncio.sleep(2)  # Wait for 2 seconds
    print(f"Data fetched from {url}")

async def main():
    task1 = asyncio.create_task(fetch_data("https://example.com"))
    task2 = asyncio.create_task(fetch_data("https://another.example.com"))

    await task1
    await task2

if __name__ == "__main__":
    asyncio.run(main())

Links