并发编程理解:Python多线程和异步IO使用示例
并发编程是指在单个处理器上同时执行多个任务。Python中提供了两种主要的并发模型:多线程(threading)和异步IO(asyncio)。
多线程:
- 使用
threading.Thread
创建线程。 - 示例代码如下:
import threading
def thread_function():
print("Thread function executed")
# 创建线程
thread = threading.Thread(target=thread_function)
# 启动线程
thread.start()
# 等待线程执行完毕
thread.join()
- 使用
异步IO:
- 使用
asyncio
库创建事件循环,事件可以是I/O操作。 - 示例代码如下:
import asyncio
@asyncio.coroutine
def io_function():
print("IO function executed")
yield from asyncio.sleep(2) # 模拟IO耗时
event_loop = asyncio.get_event_loop()
try:
task = event_loop.create_task(io_function())
task.add_done_callback(lambda task: print(f"Task done: {task}")))
# 运行事件循环
event_loop.run_forever()
except KeyboardInterrupt:
event_loop.close()
- 使用
以上就是Python多线程和异步IO的基本理解和使用示例。
还没有评论,来说两句吧...