- Python 基础
- Python - 首页
- Python - 概述
- Python - 历史
- Python - 特性
- Python vs C++
- Python - Hello World 程序
- Python - 应用领域
- Python - 解释器
- Python - 环境搭建
- Python - 虚拟环境
- Python - 基本语法
- Python - 变量
- Python - 数据类型
- Python - 类型转换
- Python - Unicode 系统
- Python - 字面量
- Python - 运算符
- Python - 算术运算符
- Python - 比较运算符
- Python - 赋值运算符
- Python - 逻辑运算符
- Python - 位运算符
- Python - 成员运算符
- Python - 身份运算符
- Python - 运算符优先级
- Python - 注释
- Python - 用户输入
- Python - 数字
- Python - 布尔值
- Python 控制语句
- Python - 控制流
- Python - 决策
- Python - if 语句
- Python - if else
- Python - 嵌套 if
- Python - match-case 语句
- Python - 循环
- Python - for 循环
- Python - for-else 循环
- Python - while 循环
- Python - break 语句
- Python - continue 语句
- Python - pass 语句
- Python - 嵌套循环
- Python 函数与模块
- Python - 函数
- Python - 默认参数
- Python - 关键字参数
- Python - 仅关键字参数
- Python - 位置参数
- Python - 仅位置参数
- Python - 可变参数
- Python - 变量作用域
- Python - 函数注解
- Python - 模块
- Python - 内置函数
- Python 字符串
- Python - 字符串
- Python - 字符串切片
- Python - 修改字符串
- Python - 字符串连接
- Python - 字符串格式化
- Python - 转义字符
- Python - 字符串方法
- Python - 字符串练习
- Python 列表
- Python - 列表
- Python - 访问列表元素
- Python - 修改列表元素
- Python - 添加列表元素
- Python - 删除列表元素
- Python - 循环遍历列表
- Python - 列表推导式
- Python - 排序列表
- Python - 复制列表
- Python - 合并列表
- Python - 列表方法
- Python - 列表练习
- Python 元组
- Python - 元组
- Python - 访问元组元素
- Python - 更新元组
- Python - 解包元组
- Python - 循环遍历元组
- Python - 合并元组
- Python - 元组方法
- Python - 元组练习
- Python 集合
- Python - 集合
- Python - 访问集合元素
- Python - 添加集合元素
- Python - 删除集合元素
- Python - 循环遍历集合
- Python - 合并集合
- Python - 复制集合
- Python - 集合运算符
- Python - 集合方法
- Python - 集合练习
- Python 字典
- Python - 字典
- Python - 访问字典元素
- Python - 修改字典元素
- Python - 添加字典元素
- Python - 删除字典元素
- Python - 字典视图对象
- Python - 循环遍历字典
- Python - 复制字典
- Python - 嵌套字典
- Python - 字典方法
- Python - 字典练习
- Python 数组
- Python - 数组
- Python - 访问数组元素
- Python - 添加数组元素
- Python - 删除数组元素
- Python - 循环遍历数组
- Python - 复制数组
- Python - 反转数组
- Python - 排序数组
- Python - 合并数组
- Python - 数组方法
- Python - 数组练习
- Python 文件处理
- Python - 文件处理
- Python - 写入文件
- Python - 读取文件
- Python - 重命名和删除文件
- Python - 目录
- Python - 文件方法
- Python - OS 文件/目录方法
- Python - OS 路径方法
- 面向对象编程
- Python - OOPs 概念
- Python - 类与对象
- Python - 类属性
- Python - 类方法
- Python - 静态方法
- Python - 构造函数
- Python - 访问修饰符
- Python - 继承
- Python - 多态
- Python - 方法重写
- Python - 方法重载
- Python - 动态绑定
- Python - 动态类型
- Python - 抽象
- Python - 封装
- Python - 接口
- Python - 包
- Python - 内部类
- Python - 匿名类和对象
- Python - 单例类
- Python - 包装类
- Python - 枚举
- Python - 反射
- Python 错误与异常
- Python - 语法错误
- Python - 异常
- Python - try-except 块
- Python - try-finally 块
- Python - 抛出异常
- Python - 异常链
- Python - 嵌套 try 块
- Python - 用户自定义异常
- Python - 日志记录
- Python - 断言
- Python - 内置异常
- Python 多线程
- Python - 多线程
- Python - 线程生命周期
- Python - 创建线程
- Python - 启动线程
- Python - 线程连接
- Python - 线程命名
- Python - 线程调度
- Python - 线程池
- Python - 主线程
- Python - 线程优先级
- Python - 守护线程
- Python - 线程同步
- Python 同步
- Python - 线程间通信
- Python - 线程死锁
- Python - 中断线程
- Python 网络编程
- Python - 网络编程
- Python - Socket 编程
- Python - URL 处理
- Python - 泛型
- Python 库
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 杂项
- Python - 日期与时间
- Python - 数学
- Python - 迭代器
- Python - 生成器
- Python - 闭包
- Python - 装饰器
- Python - 递归
- Python - 正则表达式
- Python - PIP
- Python - 数据库访问
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 输出格式化
- Python - 性能测量
- Python - 数据压缩
- Python - CGI 编程
- Python - XML 处理
- Python - GUI 编程
- Python - 命令行参数
- Python - 文档字符串
- Python - JSON
- Python - 发送邮件
- Python - 扩展
- Python - 工具/实用程序
- Python - GUIs
- Python 高级概念
- Python - 抽象基类
- Python - 自定义异常
- Python - 高阶函数
- Python - 对象内部
- Python - 内存管理
- Python - 元类
- Python - 使用元类进行元编程
- Python - 模拟和存根
- Python - 猴子补丁
- Python - 信号处理
- Python - 类型提示
- Python - 自动化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 协程
- Python - 描述符
- Python - 诊断和修复内存泄漏
- Python - 不可变数据结构
- Python 有用资源
- Python - 问答
- Python - 在线测试
- Python - 快速指南
- Python - 参考
- Python - 速查表
- Python - 项目
- Python - 有用资源
- Python - 讨论
- Python 编译器
- NumPy 编译器
- Matplotlib 编译器
- SciPy 编译器
Python - 多线程
在 Python 中,多线程允许你在单个进程中并发运行多个线程,这也称为基于线程的并行性。这意味着程序可以同时执行多个任务,从而提高效率和响应速度。
Python 中的多线程尤其适用于多个 I/O 绑定操作,而不是需要大量计算的任务。
通常,计算机程序按顺序执行指令,从开始到结束。而多线程将主要任务划分为多个子任务,并以重叠的方式执行它们。
与进程的比较
操作系统能够并发处理多个进程。它为每个进程分配单独的内存空间,以便一个进程无法访问或写入其他进程的空间。
另一方面,线程可以被认为是单个程序中共享分配给它的内存空间的轻量级子进程,这使得通信和数据共享更容易。由于它们是轻量级的并且不需要大量的内存开销;它们比进程更经济。
进程总是从单个线程(主线程)开始。根据需要,可以启动一个新线程,并将子任务委派给它。现在这两个线程以重叠的方式工作。当分配给辅助线程的任务完成后,它将与主线程合并。
线程有开始、执行序列和结束。它有一个指令指针,用于跟踪它当前在其上下文中运行的位置。
它可以被抢占(中断)
它可以暂时被挂起(也称为休眠),而其他线程正在运行——这称为让步。
Python 中的线程处理模块
Python 的标准库提供了两个主要的模块来管理线程:_thread 和 threading。
_thread 模块
_thread 模块,也称为低级线程模块,自 Python 2 版本以来一直是 Python 标准库的一部分。它提供了一个基本的线程管理 API,支持在共享全局数据空间中并发执行线程。该模块包含用于同步目的的简单锁(互斥锁)。
threading 模块
threading 模块于 Python 2.4 中引入,它基于 _thread 提供更高级、更全面的线程 API。它提供了强大的线程管理工具,使在 Python 应用程序中使用线程更容易。
threading 模块的关键特性
threading 模块公开了 thread 模块的所有方法,并提供了一些附加方法:
- threading.activeCount() - 返回活动线程对象的数目。
- threading.currentThread() - 返回调用方线程控制中的线程对象数目。
- threading.enumerate() - 返回当前活动的所有线程对象的列表。
除了这些方法外,threading 模块还有一个实现 threading 的 Thread 类。Thread 类提供的方法如下:
- run() - run() 方法是线程的入口点。
- start() - start() 方法通过调用 run 方法来启动线程。
- join([time]) - join() 方法等待线程终止。
- isAlive() - isAlive() 方法检查线程是否仍在执行。
- getName() - getName() 方法返回线程的名称。
- setName() - setName() 方法设置线程的名称。
启动新线程
要在 Python 中创建和启动新线程,可以使用低级 _thread 模块或高级 threading 模块。由于其附加功能和易用性,通常推荐使用 threading 模块。下面,您可以看到两种方法。
使用 _thread 模块启动新线程
_thread 模块的 start_new_thread() 方法提供了一种创建和启动新线程的基本方法。此方法提供了一种在 Linux 和 Windows 中快速有效地创建新线程的方法。以下是该方法的语法:
thread.start_new_thread(function, args[, kwargs] )
此方法调用立即返回,新线程开始使用给定的参数执行指定的函数。函数返回时,线程终止。
示例
此示例演示如何使用 _thread 模块创建和运行线程。每个线程都使用不同的参数运行 print_name 函数。time.sleep(0.5) 调用确保主程序在退出之前等待线程完成执行。
import _thread import time def print_name(name, *arg): print(name, *arg) name="Tutorialspoint..." _thread.start_new_thread(print_name, (name, 1)) _thread.start_new_thread(print_name, (name, 1, 2)) time.sleep(0.5)
执行上述代码时,会产生以下结果:
Tutorialspoint... 1 Tutorialspoint... 1 2
虽然它对于低级线程非常有效,但与提供更多功能和更高级线程管理的 threading 模块相比,_thread 模块的功能有限。
使用 threading 模块启动新线程
threading 模块提供 Thread 类,用于创建和管理线程。
以下是使用 threading 模块启动新线程的几个步骤:
- 创建一个希望线程执行的函数。
- 然后,通过传递目标函数及其参数,使用 Thread 类创建一个 Thread 对象。
- 调用 Thread 对象上的 start 方法开始执行。
- 可选:调用 join 方法以等待线程完成,然后再继续执行。
示例
以下示例演示如何使用 threading 模块创建和启动线程。它运行一个 print_name 函数,该函数打印名称以及一些参数。此示例创建两个线程,使用 start() 方法启动它们,并使用 join 方法等待它们完成。
import threading
import time
def print_name(name, *args):
print(name, *args)
name = "Tutorialspoint..."
# Create and start threads
thread1 = threading.Thread(target=print_name, args=(name, 1))
thread2 = threading.Thread(target=print_name, args=(name, 1, 2))
thread1.start()
thread2.start()
# Wait for threads to complete
thread1.join()
thread2.join()
print("Threads are finished...exiting")
执行上述代码时,会产生以下结果:
Tutorialspoint... 1 Tutorialspoint... 1 2 Threads are finished...exiting
线程同步
Python 提供的 threading 模块包含一个易于实现的锁定机制,允许你同步线程。通过调用 Lock() 方法创建一个新的锁,该方法返回新的锁。
新锁对象的 acquire(blocking) 方法用于强制线程同步运行。可选的 blocking 参数允许你控制线程是否等待获取锁。
如果 blocking 设置为 0,则如果无法获取锁,线程立即返回 0 值;如果获取了锁,则返回 1。如果 blocking 设置为 1,则线程阻塞并等待锁释放。
新锁对象的 release() 方法用于在不再需要锁时释放锁。
示例
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print ("Exiting Main Thread")
执行上述代码时,会产生以下结果:
Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11:28 2013 Thread-1: Thu Mar 21 09:11:29 2013 Thread-1: Thu Mar 21 09:11:30 2013 Thread-2: Thu Mar 21 09:11:32 2013 Thread-2: Thu Mar 21 09:11:34 2013 Thread-2: Thu Mar 21 09:11:36 2013 Exiting Main Thread
多线程优先级队列
Queue 模块允许你创建一个可以容纳特定数量项的新队列对象。以下是控制队列的方法:
get() - get() 从队列中移除并返回一个项。
put() - put() 将项添加到队列。
qsize() - qsize() 返回当前在队列中的项数。
empty() - empty() 如果队列为空则返回 True;否则返回 False。
full() - full() 如果队列已满则返回 True;否则返回 False。
示例
import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print ("Starting " + self.name)
process_data(self.name, self.q)
print ("Exiting " + self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("%s processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print ("Exiting Main Thread")
执行上述代码时,会产生以下结果:
Starting Thread-1 Starting Thread-2 Starting Thread-3 Thread-1 processing One Thread-2 processing Two Thread-3 processing Three Thread-1 processing Four Thread-2 processing Five Exiting Thread-3 Exiting Thread-1 Exiting Thread-2 Exiting Main Thread