并发编程是提高程序性能的关键技术之一。在 Python 中,有多种方式可以实现并发编程,包括多线程、多进程以及异步编程。本文将介绍 Python 中常用的并发编程方法。
1. 多线程
Python 的 threading
模块提供了线程的支持。线程可以在同一进程中并发执行,但 Python 的全局解释器锁(GIL)限制了同一时刻只有一个线程执行 Python 代码。
- 创建线程
import threading
def print_numbers():
for i in range(10):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
- 线程同步
当多个线程需要访问共享资源时,需要使用线程同步机制,如锁(Lock)。
import threading
lock = threading.Lock()
def print_numbers():
for i in range(10):
with lock:
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
2. 多进程
multiprocessing
模块提供了多进程的支持。与线程相比,进程可以运行在多个 CPU 核心上,从而提高程序的性能。
- 创建进程
from multiprocessing import Process
def print_numbers():
for i in range(10):
print(i)
process = Process(target=print_numbers)
process.start()
process.join()
- 进程间通信
进程间通信可以使用 multiprocessing
模块提供的 Queue
或 Pipe
。
from multiprocessing import Process, Queue
def producer(queue):
for i in range(10):
queue.put(i)
def consumer(queue):
while True:
num = queue.get()
if num is None:
break
print(num)
queue = Queue()
producer_process = Process(target=producer, args=(queue,))
consumer_process = Process(target=consumer, args=(queue,))
producer_process.start()
consumer_process.start()
producer_process.join()
consumer_process.join()
3. 异步编程
asyncio
模块是 Python 3.4 及以上版本提供的异步编程库。使用 asyncio
可以编写单线程的并发程序,利用 await
关键字实现异步调用。
- 创建异步任务
import asyncio
async def print_numbers():
for i in range(10):
print(i)
async def main():
await print_numbers()
asyncio.run(main())
- 异步协程
异步协程是 asyncio
中的基本执行单元,可以通过 async def
定义。
async def print_numbers():
for i in range(10):
print(i)
async def main():
await print_numbers()
asyncio.run(main())
扩展阅读
更多关于 Python 并发编程的内容,可以参考以下链接:
希望本文能帮助您了解 Python 并发编程。😊