Create_task() Function Of Asyncio Module In Python


  • 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 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):
        msg = file.readline()
        if not 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")
        # 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()
        # coroutine yields after every write        
        await asyncio.sleep(0)    


# 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()

# Now run the tasks(in the event loop)







Copyright 2022 ©