Python中协程间通信的方式小结

 更新时间:2025年01月09日 14:46:08   作者:Toormi  
Python中协程间的通信方式包括asyncio.Queue、asyncio.Event、asyncio.Condition、asyncio.Semaphore、asyncio.Streams和asyncio.Future,感兴趣的可以了解一下

在 Python 中,协程间的通信主要依赖于以下几种方式:

1. asyncio.Queue

asyncio.Queue 是 Python asyncio 库提供的一个线程安全的队列,用于在协程之间传递数据。与常规的队列类似,但它支持异步操作,即可以在协程内等待队列中的数据。

示例:

import asyncio

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

async def consumer(queue):
    while True:
        item = await queue.get()
        if item is None:  # 用 None 表示终止信号
            break
        print(f"Consumed: {item}")
        await asyncio.sleep(2)

async def main():
    queue = asyncio.Queue()
    await asyncio.gather(producer(queue), consumer(queue))

asyncio.run(main())

2. asyncio.Event

asyncio.Event 是一个简单的同步原语,允许一个协程等待某个事件的发生,另一个协程则负责设置该事件。通常用于通知其他协程某些状态发生变化。

示例:

import asyncio

async def waiter(event):
    print("Waiting for event...")
    await event.wait()  # 阻塞直到事件被触发
    print("Event occurred!")

async def setter(event):
    await asyncio.sleep(2)
    print("Setting event!")
    event.set()  # 设置事件

async def main():
    event = asyncio.Event()
    await asyncio.gather(waiter(event), setter(event))

asyncio.run(main())

3. asyncio.Condition

asyncio.Condition 类似于线程中的 Condition,允许一个或多个协程等待某个条件的变化。它可以与锁结合使用。

示例:

import asyncio

async def consumer(condition, shared_data):
    async with condition:
        while shared_data["item"] is None:
            await condition.wait()  # 等待条件
        print(f"Consumed: {shared_data['item']}")
        shared_data["item"] = None

async def producer(condition, shared_data):
    await asyncio.sleep(1)
    async with condition:
        shared_data["item"] = "Apple"
        condition.notify()  # 通知等待的协程
        print(f"Produced: {shared_data['item']}")

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

asyncio.run(main())

4. asyncio.Semaphore

asyncio.Semaphore 是一个计数信号量,控制并发访问的协程数目。适用于限制协程的并发数量。

示例:

import asyncio

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

async def main():
    sem = asyncio.Semaphore(2)  # 最多同时运行2个协程
    tasks = [task(sem) for _ in range(5)]
    await asyncio.gather(*tasks)

asyncio.run(main())

5. asyncio.Streams (StreamReader 和 StreamWriter)

StreamReader 和 StreamWriter 是用于网络通信的流接口,适用于两个协程之间通过网络协议传输数据的场景。尽管它们主要用于处理网络 I/O,但也可以用于在协程之间传输数据。

示例:

import asyncio

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

    print("Send: %r" % message)
    writer.write(data)
    await writer.drain()

    print("Closing the connection")
    writer.close()

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

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

    async with server:
        await server.serve_forever()

asyncio.run(main())

6. asyncio.Future

asyncio.Future 类似于 Promise,它表示一个尚未完成的操作。一个协程可以将其结果存储在 Future 对象中,而其他协程可以等待该 Future 对象完成。

示例:

import asyncio

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

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

async def main():
    future = asyncio.Future()
    await asyncio.gather(set_future(future), get_future(future))

asyncio.run(main())

这些通信方式各有其特定的用途,可以根据不同的场景选择合适的方式来进行协程间的通信。

到此这篇关于Python中协程间通信的方式小结的文章就介绍到这了,更多相关Python 协程间通信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python3中条件控制、循环与函数的简易教程

    Python3中条件控制、循环与函数的简易教程

    这篇文章主要给大家介绍了关于Python3中条件控制、循环与函数的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2017-11-11
  • python实现启动一个外部程序,并且不阻塞当前进程

    python实现启动一个外部程序,并且不阻塞当前进程

    这篇文章主要介绍了python实现启动一个外部程序,并且不阻塞当前进程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • 使用tensorflow实现线性回归

    使用tensorflow实现线性回归

    这篇文章主要为大家详细介绍了使用tensorflow实现线性回归,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-09-09
  • 关于python字符串方法分类详解

    关于python字符串方法分类详解

    在本篇文章里小编给各位整理的是关于关于python字符串方法分类的知识点内容,有兴趣的朋友们学习下。
    2019-08-08
  • Python OpenCV实现裁剪并保存图片

    Python OpenCV实现裁剪并保存图片

    这篇文章主要为大家详细介绍了Python OpenCV实现裁剪并保存图片,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-07-07
  • 深入浅析Python 函数注解与匿名函数

    深入浅析Python 函数注解与匿名函数

    这篇文章主要介绍了Python 函数注解与匿名函数的相关知识,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02
  • python+Splinter实现12306抢票功能

    python+Splinter实现12306抢票功能

    这篇文章主要为大家详细介绍了python+Splinter实现12306抢票功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-09-09
  • 利用Python判断整数是否是回文数的3种方法总结

    利用Python判断整数是否是回文数的3种方法总结

    这篇文章主要给大家介绍了关于如何利用Python判断整数是否是回文数的3种方总结,回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数,需要的朋友可以参考下
    2021-07-07
  • Python中type()函数的具体使用

    Python中type()函数的具体使用

    在Python中,type()函数是一个非常有用的工具,它可以查看变量或对象的数据类型,本文主要介绍了Python中type()函数的具体使用,感兴趣的可以一起来了解一下
    2024-01-01
  • Python实现文件操作帮助类的示例代码

    Python实现文件操作帮助类的示例代码

    在使用Python进行业务开发的时候,需要将一些数据保存到本地文件存储,方便后面进行数据分析展示,本文就来用Python制作一个文件操作帮助类,需要的可以参考一下
    2023-03-03

最新评论