多线程可提升I/O密集型任务效率,threading模块为核心工具。1. 用Lock避免数据竞争,with语句确保安全加锁释放;2. 通过target或继承Thread创建线程,灵活适配任务需求;3. 调用start启动线程,join等待完成,daemon=True设守护线程;4. 使用Queue实现线程安全通信,支持生产者-消费者模型。注意GIL限制CPU并发,需合理设计线程数、避免死锁、优先队列通信以保证程序稳定高效。
在Python中使用多线程可以提升I/O密集型任务的执行效率,而threading模块是实现多线程编程的核心工具。掌握一些实用技巧能让线程操作更安全、高效。
多个线程访问共享资源时容易引发数据不一致问题,使用threading.Lock能有效保护临界区。
说明:Lock保证同一时间只有一个线程可以执行被保护的代码段。
建议用法:
import threadinglock = threading.Lock() counter = 0
def increment(): global counter with lock: counter += 1 # 安全修改共享变量
创建线程有两种常用方式:通过target指定函数,或继承threading.Thread类。
适用场景:
def worker(name):
print(f"线程 {name} 正在运行")
t = threading.Thread(target=worker, args=("A",))
t.start()
t.join() # 等待线程结束
示例 - 继承Thread:
class MyThread(threading.Thread):
def run(self):
print(f"{self.name} 执行中")
t = MyThread()
t.start()
理解线程的启动与等待机制对程序稳定性很重要。
关键点:
t= threading.Thread(target=worker, daemon=True) t.start() # 主线程结束时,t会自动终止
queue.Queue是线程安全的队列,适合在多线程间传递数据。
优势:
from queue import Queueq = Queue()
def producer(): for i in range(5): q.put(i)
def consumer(): while True: item = q.get() if item is None: break print(f"消费: {item}") q.task_done()
启动线程...
基本上就这些。threading模块功能强大,但要注意GIL限制了CPU密集型任务的并发效果。合理设计线程数量、避免死锁、优先使用队列通信,才能写出稳定高效的多线程程序。