Create_task() Function Of Asyncio Module In Python

Overview:

  • The asyncio module of Python enables executing coroutines through Tasks and Futures.

  • A coroutine is expected to be suspended several times as it yields the CPU, while waiting for an awaitable object to do some processing.

  • To execute a single coroutine or multiple coroutines several times, a programmer can not code all of the start/resume sequence(suspend is taken care by the coroutine itself) line by line. Instead, a loop can execute them. asyncio offers this loop, which is called an event loop that executes the coroutines through Task objects.

  • The computations done by a coroutine are abstracted as a Task in the asyncio.

  • The create_task() function of the asyncio module creates and returns a Task from a coroutine. These Task instances are executed by the event loop provided by the Python's asyncio module.

  • It is required to have an event loop created before calling create_task(). The Task is created and executed on this event loop.

  • The asyncio module allows custom event loops to be used for the task execution.

Example:

# Example Python program that executes
# coroutines as Tasks using the 
# event loop provided by the asyncio
import asyncio

# A list of messages
msgs         = []

# A list of new messages
newmsgs     = []

# Source file
fileOb      = open("./Tokens1.txt")

# Target file
wfileOb      = open("./NewTokens.txt","w")

# Coroutine that reads messages from
# a file and appends to a Python list
async def readMessages(file, msgcol):
    while(True):
        msg = file.readline()
        if not msg:
            break
        else: 
            msgcol.append(msg)
            #print("R:%s"%msg)
            # Make the coroutine to yield
            await asyncio.sleep(0)

# Coroutine that transforms messages
# and appends to another Python list
async def transformMessages(msgcol, nmsgcol):
    while(len(msgcol) > 0):
        msg = msgcol.pop()    
        nmsg = msg.encode(encoding="ascii")
        nmsgcol.append(nmsg)
        #print("T:%s"%nmsg)
        # coroutine yielding the CPU
        await asyncio.sleep(0)    

# Coroutine that reads the transformed
# messages from the list and writes to a file
async def writeMessages(nfile, nmsgcol):
    while(len(nmsgcol) > 0):
        #print("NewMessage Count:%d"%len(nmsgcol))
        nmsg = nmsgcol.pop()
        nfile.write(nmsg.decode())
        # coroutine yields after every write        
        await asyncio.sleep(0)    

        #print("W:%s"%nmsg)

# A coroutine that creates tasks and waits on them
async def main():
    t1 = asyncio.create_task(readMessages(fileOb, msgs))
    t2 = asyncio.create_task(transformMessages(msgs, newmsgs))
    t3 = asyncio.create_task(writeMessages(wfileOb, newmsgs))
    
    # Run mutiple asyncio.Task instances
    await asyncio.wait([t1,t2,t3])

# Create a new event loop and make it to run the tasks
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

# Now run the tasks(in the event loop) 
asyncio.run(main())

Output:

a1

b1

c1

d1

 


Copyright 2023 © pythontic.com