题目
使用threading模块创建并启动两个线程
信息
- 类型:问答
- 难度:⭐
考点
多线程基础,threading模块使用,线程启动方法
快速回答
在Python中创建和启动线程的基本步骤:
- 导入
threading模块 - 定义线程执行函数
- 创建
Thread对象并绑定函数 - 调用
start()方法启动线程 - 使用
join()等待线程结束(可选)
原理说明
Python通过threading模块实现多线程编程。每个Thread对象代表一个独立执行流,由操作系统调度。注意:由于GIL(全局解释器锁)的存在,Python线程适合I/O密集型任务,而非CPU密集型任务。
代码示例
import threading
import time
# 定义线程任务函数
def print_numbers():
for i in range(1, 6):
time.sleep(0.1) # 模拟耗时操作
print(f'Number: {i}')
def print_letters():
for char in 'ABCDE':
time.sleep(0.1)
print(f'Letter: {char}')
# 创建线程对象
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
print("All threads completed")最佳实践
- 使用
target参数绑定无状态函数 - 线程函数应避免修改共享数据(需要时用锁)
- 使用
join()确保主线程等待子线程结束 - 为线程设置
daemon=True可创建守护线程(主退出即终止)
常见错误
- 错误1:调用
run()而非start()(导致顺序执行) - 错误2:忽略GIL限制,在CPU密集型任务中使用线程
- 错误3:多个线程无保护地修改共享变量
- 错误4:主线程提前退出导致子线程中断
扩展知识
- GIL影响:同一时刻仅一个线程执行Python字节码
- 线程通信:使用
queue.Queue安全传递数据 - 替代方案:CPU密集型任务考虑
multiprocessing模块 - 线程池:
concurrent.futures.ThreadPoolExecutor高效管理线程