Python并发编程:多线程和异步IO示例
在Python中,我们可以使用两种主要的并发模型:多线程(Thread)和异步IO(Asynchronous I/O)。
- 多线程示例:
```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()
2. 异步IO示例:
```python
import asyncio
# 定义一个异步函数
async def my_async_function():
print("Async function is running...")
await asyncio.sleep(2) # 模拟耗时操作
# 创建事件循环
loop = asyncio.get_event_loop()
# 异步执行函数
task = loop.create_task(my_async_function())
try:
task.wait() # 等待任务完成
except KeyboardInterrupt:
loop.stop() # 停止事件循环以响应中断
这两种方法都允许程序同时执行多个任务,提高了并发性能。
还没有评论,来说两句吧...