Python并发编程:多线程和异步IO示例

原创 电玩女神 2025-03-01 22:30 42阅读 0赞

在Python中,我们可以使用两种主要的并发模型:多线程(Thread)和异步IO(Asynchronous I/O)。

  1. 多线程示例:
    ```python
    import threading

定义一个要运行的函数

def my_function():
print(f”Thread {threading.current_thread().name} is running…”)

创建线程

thread1 = threading.Thread(target=my_function)
thread2 = threading.Thread(target=my_function)

启动线程

thread1.start()
thread2.start()

等待所有线程结束

thread1.join()
thread2.join()

  1. 2. 异步IO示例:
  2. ```python
  3. import asyncio
  4. # 定义一个异步函数
  5. async def my_async_function():
  6. print("Async function is running...")
  7. await asyncio.sleep(2) # 模拟耗时操作
  8. # 创建事件循环
  9. loop = asyncio.get_event_loop()
  10. # 异步执行函数
  11. task = loop.create_task(my_async_function())
  12. try:
  13. task.wait() # 等待任务完成
  14. except KeyboardInterrupt:
  15. loop.stop() # 停止事件循环以响应中断

这两种方法都允许程序同时执行多个任务,提高了并发性能。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,42人围观)

还没有评论,来说两句吧...

相关阅读