SoFunction
Updated on 2025-03-06

Summary of the communication between coroutines in Python

In Python, communication between coroutines mainly depends on the following methods:

1. 

Yes PythonasyncioA thread-safe queue provided by the library to pass data between coroutines. Similar to regular queues, but it supports asynchronous operations, i.e. waiting for data in the queue within a coroutine.

Example:

import asyncio

async def producer(queue):
    for i in range(5):
        await (i)
        print(f"Produced: {i}")
        await (1)

async def consumer(queue):
    while True:
        item = await ()
        if item is None:  # Use None to indicate the termination signal            break
        print(f"Consumed: {item}")
        await (2)

async def main():
    queue = ()
    await (producer(queue), consumer(queue))

(main())

2. 

It is a simple synchronization primitive that allows a coroutine to wait for an event to occur, while another coroutine is responsible for setting the event. Usually used to notify other coroutines that some state changes.

Example:

import asyncio

async def waiter(event):
    print("Waiting for event...")
    await ()  # Block until the event is triggered    print("Event occurred!")

async def setter(event):
    await (2)
    print("Setting event!")
    ()  # Set events
async def main():
    event = ()
    await (waiter(event), setter(event))

(main())

3. 

Similar to the threadCondition, allowing one or more coroutines to wait for a change in a certain condition. It can be used in conjunction with locks.

Example:

import asyncio

async def consumer(condition, shared_data):
    async with condition:
        while shared_data["item"] is None:
            await ()  # Waiting for conditions        print(f"Consumed: {shared_data['item']}")
        shared_data["item"] = None

async def producer(condition, shared_data):
    await (1)
    async with condition:
        shared_data["item"] = "Apple"
        ()  # Notify waiting coroutines        print(f"Produced: {shared_data['item']}")

async def main():
    shared_data = {"item": None}
    condition = ()
    await (producer(condition, shared_data), consumer(condition, shared_data))

(main())

4. 

is a counting semaphore that controls the number of coroutines to be accessed concurrently. Applicable to limit the number of concurrency in coroutines.

Example:

import asyncio

async def task(sem):
    async with sem:
        print("Task started")
        await (1)
        print("Task completed")

async def main():
    sem = (2)  # Run up to 2 coroutines at the same time    tasks = [task(sem) for _ in range(5)]
    await (*tasks)

(main())

5.  (StreamReader and StreamWriter)

StreamReaderandStreamWriterIt is a stream interface for network communication, suitable for scenarios where data is transmitted between two coroutines through network protocols. Although they are mainly used to handle network I/O, they can also be used to transfer data between coroutines.

Example:

import asyncio

async def echo(reader, writer):
    data = await (100)
    message = ()
    addr = writer.get_extra_info('peername')
    print(f"Received {message} from {addr}")

    print("Send: %r" % message)
    (data)
    await ()

    print("Closing the connection")
    ()

async def main():
    server = await asyncio.start_server(
        echo, '127.0.0.1', 8888)

    addr = [0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()

(main())

6. 

Similar toPromise, it represents an operation that has not been completed. A coroutine can store its results inFutureIn the object, other coroutines can wait for theFutureObject is completed.

Example:

import asyncio

async def set_future(future):
    await (1)
    future.set_result('Hello from Future!')

async def get_future(future):
    result = await future
    print(f"Got result: {result}")

async def main():
    future = ()
    await (set_future(future), get_future(future))

(main())

These communication methods each have their own specific uses, and appropriate methods can be selected according to different scenarios to conduct communication between coroutines.

This is the article about the summary of the communication between coroutines in Python. For more related contents of inter-coroutines, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!