如何使用 Python 并发编程来同时绘制一个圆形和一个方形?
时间: 2024-11-24 09:41:07 浏览: 0
计算机图形学-使用Python的OpenGL库绘制一个旋转的立方体
在Python中,你可以利用`concurrent.futures`模块或者`threading`模块来实现并发绘制圆形和方形。这里我们使用`ThreadPoolExecutor`从`concurrent.futures`库,它允许在多个线程之间共享任务:
```python
import concurrent.futures
from threading import Thread
import time
import matplotlib.pyplot as plt
# 创建一个简单的绘图函数
def draw_shape(shape_name):
fig, ax = plt.subplots()
if shape_name == 'circle':
circle = plt.Circle((0.5, 0.5), 0.4, color='red')
ax.add_artist(circle)
elif shape_name == 'square':
square = plt.Rectangle((0.1, 0.1), 0.8, 0.8, fill=True, color='blue')
ax.add_patch(square)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.pause(1) # 暂停一段时间以让形状可见
plt.close() # 关闭当前图形窗口
# 使用线程池并行绘制
shapes = ['circle', 'square']
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
future_to_shape = {executor.submit(draw_shape, shape): shape for shape in shapes}
for future in concurrent.futures.as_completed(future_to_shape):
shape = future_to_shape[future]
try:
future.result() # 等待结果完成
except Exception as exc:
print(f'{shape} drawing failed: {exc}')
阅读全文