苏州建设交通学校网站,昆明网站建设网站,上海何时开放娱乐场所,网站空间多少钱一年Python笔记之线程库threading 参考博文 Python多线程笔记——简单函数版和类实现版
code review!
Python 的 threading 库用于在程序中创建和管理线程。线程允许程序并发执行多个任务。以下是 threading 库的详解和一些简洁示例。
基本概念
线程#xff1a;在一个进程中在一个进程中一个线程是执行指令的单独路径。主线程每个程序启动时都会有一个默认的主线程。GIL全局解释器锁Python 的线程受到 GIL 的限制不能真正并行地运行 CPU 绑定的任务但在 I/O 密集型任务中仍然可以提高性能。
重要类和方法
Thread 类用于创建线程。 start(): 开始线程活动。join(): 阻塞调用线程直到被调用的线程终止。run(): 线程活动的方法。 Lock 类用于线程间同步防止竞争条件。RLock 类可重入锁允许在同一线程中多次获得锁。Condition 类用于线程间通信。Semaphore 类控制对共享资源的访问。Event 类用于线程间信号通信。
简单示例
1. 创建并启动线程
import threadingdef print_numbers():for i in range(5):print(i)# 创建线程
thread threading.Thread(targetprint_numbers)# 启动线程
thread.start()# 等待线程完成
thread.join()print(Thread has finished execution.)2. 使用锁同步线程
import threadingcounter 0
lock threading.Lock()def increment_counter():global counterwith lock:for _ in range(10000):counter 1threads [threading.Thread(targetincrement_counter) for _ in range(2)]for thread in threads:thread.start()for thread in threads:thread.join()print(fFinal counter value: {counter})3. 创建自定义线程类
import threadingclass MyThread(threading.Thread):def run(self):for i in range(5):print(fThread {self.name}: {i})# 实例化并启动自定义线程
thread MyThread()
thread.start()
thread.join()注意事项
线程安全在访问共享数据时使用锁确保线程安全。性能对于 CPU 密集型任务考虑使用 multiprocessing 模块。调试调试多线程程序可能会比较困难可以使用日志记录来帮助调试。
这些示例展示了如何使用 threading 库创建和管理线程以及如何解决常见的同步问题。