Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python asyncio gather

import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({number}), currently i={i}...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")
    return f

async def main():
    # Schedule three calls *concurrently*:
    L = await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )
    print(L)

asyncio.run(main())

# Expected output:
#
#     Task A: Compute factorial(2), currently i=2...
#     Task B: Compute factorial(3), currently i=2...
#     Task C: Compute factorial(4), currently i=2...
#     Task A: factorial(2) = 2
#     Task B: Compute factorial(3), currently i=3...
#     Task C: Compute factorial(4), currently i=3...
#     Task B: factorial(3) = 6
#     Task C: Compute factorial(4), currently i=4...
#     Task C: factorial(4) = 24
#     [2, 6, 24]
Comment

asyncio.gather

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")
Comment

PREVIOUS NEXT
Code Example
Python :: splitting column values in pandas 
Python :: install django in windows 
Python :: starting variable name with underscore python 
Python :: ModuleNotFoundError: No module named 
Python :: list deep copy 
Python :: remove multiple elements from a list in python 
Python :: python for loop in array 
Python :: or statement python 
Python :: get ip address python 
Python :: settings.debug django 
Python :: append write python 
Python :: what is a print statement 
Python :: how to change int to four decimal places in python 
Python :: make widget span window width tkinter 
Python :: translate french to english 
Python :: calculate term frequency python 
Python :: python string cut right 
Python :: python delete all occurrences from list 
Python :: django serve media folder 
Python :: neural network hyperparameter tuning 
Python :: timedelta python 
Python :: hashmap python 
Python :: seaborn plot histogram for all columns 
Python :: python pandas read_excel 
Python :: python binary search 
Python :: selenium undetected chromedriver error 
Python :: python convert object to json 
Python :: pytest local modules 
Python :: change key of dictionary python 
Python :: python error handling 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =