Python启航:30天编程速成之旅(第23天)- 多线程从入门到精通
bigegpt 2024-12-19 11:30 3 浏览
喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。
前期基础教程:
「Python3.11.0」手把手教你安装最新版Python运行环境
讲讲Python环境使用Pip命令快速下载各类库的方法
Python启航:30天编程速成之旅(第2天)-IDE安装
【Python教程】JupyterLab 开发环境安装
Python启航:30天编程速成之旅(第23天)- 多线程从入门到精通
简介
什么是多线程?
多线程是指一个程序中可以同时运行多个线程。每个线程是程序的一个独立执行路径,可以并行执行任务。多线程允许多个任务在同一个进程中并发执行,从而提高程序的效率和响应速度。
为什么使用多线程?
- 提高程序的响应性:例如,在 GUI 应用中,主线程负责处理用户界面,而其他线程可以执行后台任务,确保用户界面不会因为长时间的任务而卡住。
- 充分利用多核 CPU:虽然 Python 的 GIL 限制了多线程在 CPU 密集型任务中的并行性,但对于 I/O 密集型任务(如网络请求、文件读写),多线程可以显著提高性能。
- 简化代码结构:通过将复杂的任务分解为多个线程,可以使代码更易于理解和维护。
Python 中的 GIL(全局解释器锁)
Python 的 CPython 解释器有一个称为 GIL(Global Interpreter Lock) 的机制,它确保同一时刻只有一个线程在执行 Python 字节码。这意味着即使你有多个 CPU 核心,Python 的多线程也无法真正实现 CPU 密集型任务的并行执行。
然而,对于 I/O 密集型任务(如网络请求、文件读写),GIL 的影响较小,因为这些任务通常会释放 GIL 以等待 I/O 操作完成。因此,多线程在 I/O 密集型任务中仍然非常有用。
初级:创建和启动线程
使用threading.Thread创建线程
Python 提供了 threading 模块来处理多线程。最简单的方式是使用 threading.Thread 类来创建和启动线程。
import threading
import time
def print_numbers():
for i in range(5):
print(f"Number: {i}")
time.sleep(1)
def print_letters():
for letter in 'ABCDE':
print(f"Letter: {letter}")
time.sleep(1)
# 创建两个线程
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_letters)
# 启动线程
t1.start()
t2.start()
# 等待线程结束
t1.join()
t2.join()
print("Both threads have finished.")
线程的基本属性和方法
- start():启动线程,调用线程的目标函数。
- join():阻塞当前线程,直到目标线程结束。这通常用于确保主线程等待所有子线程完成。
- is_alive():检查线程是否正在运行。
- name:获取或设置线程的名称。
- daemon:设置线程是否为守护线程。守护线程会在主线程结束时自动终止。
线程的生命周期
线程的生命周期包括以下几个阶段:
- 新建:线程对象被创建,但尚未启动。
- 就绪:线程已经启动,等待调度器分配 CPU 时间。
- 运行:线程正在执行。
- 阻塞:线程暂时停止执行,等待某个条件(如 I/O 操作完成)。
- 死亡:线程执行完毕或被终止。
中级:线程同步与通信
当多个线程同时访问共享资源时,可能会导致数据不一致或竞争条件(race condition)。为了防止这种情况,Python 提供了多种同步机制。
锁(Lock)与互斥锁(RLock)
Lock 是最简单的同步原语,用于确保一次只有一个线程可以访问共享资源。
import threading
import time
lock = threading.Lock()
def thread_function(name):
with lock:
print(f"Thread {name} is acquiring the lock.")
time.sleep(1)
print(f"Thread {name} is releasing the lock.")
# 创建多个线程
threads = []
for i in range(3):
t = threading.Thread(target=thread_function, args=(i,))
threads.append(t)
t.start()
# 等待所有线程结束
for t in threads:
t.join()
RLock(可重入锁)允许同一线程多次获取锁,而不会导致死锁。
rlock = threading.RLock()
with rlock:
# 可以再次获取同一锁
with rlock:
print("This is safe with RLock.")
条件变量(Condition)
Condition 对象用于在线程之间进行更复杂的通信。它可以用来等待某个条件成立,或者通知其他线程条件已经满足。
import threading
import time
condition = threading.Condition()
data = []
def producer():
for i in range(5):
with condition:
data.append(i)
print(f"Produced: {i}")
condition.notify() # 通知消费者
time.sleep(1)
def consumer():
for _ in range(5):
with condition:
condition.wait() # 等待生产者
item = data.pop(0)
print(f"Consumed: {item}")
# 创建生产者和消费者线程
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t2.start()
t1.join()
t2.join()
事件(Event)
Event 对象用于在线程之间传递简单的信号。一个线程可以设置或清除事件,另一个线程可以等待事件的发生。
import threading
import time
event = threading.Event()
def wait_for_event():
print("Waiting for event...")
event.wait() # 等待事件发生
print("Event occurred!")
def set_event():
time.sleep(3)
print("Setting event...")
event.set() # 触发事件
# 创建线程
t1 = threading.Thread(target=wait_for_event)
t2 = threading.Thread(target=set_event)
t1.start()
t2.start()
t1.join()
t2.join()
队列(Queue)
Queue 是一个线程安全的队列,适用于生产者-消费者模式。生产者线程将数据放入队列,消费者线程从队列中取出数据。
from queue import Queue
import threading
import time
queue = Queue()
def producer(queue):
for i in range(5):
queue.put(i)
print(f"Produced: {i}")
time.sleep(1)
def consumer(queue):
while True:
item = queue.get()
if item is None:
break
print(f"Consumed: {item}")
queue.task_done()
# 创建生产者和消费者线程
t1 = threading.Thread(target=producer, args=(queue,))
t2 = threading.Thread(target=consumer, args=(queue,))
t1.start()
t2.start()
t1.join()
queue.put(None) # 发送终止信号给消费者
t2.join()
高级:线程池与并发编程
使用concurrent.futures模块
concurrent.futures 模块提供了一个高层次的接口来管理线程池和进程池。它简化了并发编程,尤其是当你需要提交多个任务时。
from concurrent.futures import ThreadPoolExecutor
import time
def task(n):
print(f"Task {n} started")
time.sleep(1)
return f"Task {n} completed"
# 创建线程池
with ThreadPoolExecutor(max_workers=3) as executor:
# 提交多个任务
futures = [executor.submit(task, i) for i in range(5)]
# 获取任务结果
for future in futures:
print(future.result())
线程池(ThreadPoolExecutor)
ThreadPoolExecutor 是 concurrent.futures 模块中的一个类,用于管理线程池。你可以指定最大线程数,并提交多个任务给线程池执行。
from concurrent.futures import ThreadPoolExecutor
import time
def download_file(url):
print(f"Downloading {url}...")
time.sleep(2)
return f"{url} downloaded"
urls = [
"https://example.com/file1",
"https://example.com/file2",
"https://example.com/file3"
]
# 创建线程池
with ThreadPoolExecutor(max_workers=3) as executor:
# 提交任务
results = list(executor.map(download_file, urls))
# 打印结果
for result in results:
print(result)
异步 I/O 与asyncio
对于 I/O 密集型任务,asyncio 提供了更高效的异步编程模型。asyncio 基于协程(coroutine),可以在单线程中实现并发操作。
import asyncio
async def fetch_data(url):
print(f"Fetching {url}...")
await asyncio.sleep(2) # 模拟网络请求
return f"{url} fetched"
async def main():
urls = [
"https://example.com/file1",
"https://example.com/file2",
"https://example.com/file3"
]
# 并发执行多个任务
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
# 打印结果
for result in results:
print(result)
# 运行异步主函数
asyncio.run(main())
并发模式:生产者-消费者模型
生产者-消费者模型是一种常见的并发模式,适用于多个生产者生成数据,多个消费者处理数据的场景。Queue 和 asyncio.Queue 都可以用于实现这种模式。
from queue import Queue
import threading
import time
queue = Queue()
def producer(queue):
for i in range(5):
queue.put(i)
print(f"Produced: {i}")
time.sleep(1)
def consumer(queue):
while True:
item = queue.get()
if item is None:
break
print(f"Consumed: {item}")
queue.task_done()
# 创建生产者和消费者线程
t1 = threading.Thread(target=producer, args=(queue,))
t2 = threading.Thread(target=consumer, args=(queue,))
t1.start()
t2.start()
t1.join()
queue.put(None) # 发送终止信号给消费者
t2.join()
性能优化与最佳实践
减少锁的竞争
锁的使用会导致线程之间的竞争,降低性能。尽量减少锁的使用范围,只在必要时加锁,并且尽量缩短持有锁的时间。
lock = threading.Lock()
def update_shared_resource(shared_resource, value):
with lock:
# 尽量减少锁的持有时间
shared_resource += value
使用multiprocessing模块绕过 GIL
对于 CPU 密集型任务,multiprocessing 模块可以通过创建多个进程来绕过 GIL 的限制。每个进程都有自己的 Python 解释器和内存空间,因此可以真正实现并行执行。
from multiprocessing import Pool
def cpu_intensive_task(x):
return sum(i * i for i in range(x))
if __name__ == '__main__':
with Pool(processes=4) as pool:
results = pool.map(cpu_intensive_task, [10000, 20000, 30000, 40000])
print(results)
线程安全的数据结构
Python 提供了一些线程安全的数据结构,如 queue.Queue、threading.local 等。使用这些数据结构可以避免手动加锁,简化代码。
from queue import Queue
queue = Queue()
def producer(queue):
for i in range(5):
queue.put(i)
print(f"Produced: {i}")
time.sleep(1)
def consumer(queue):
while True:
item = queue.get()
if item is None:
break
print(f"Consumed: {item}")
queue.task_done()
性能分析与调试
使用 cProfile 或 line_profiler 等工具可以帮助你分析代码的性能瓶颈。对于多线程程序,还可以使用 threading.settrace() 来跟踪线程的执行情况。
import cProfile
import pstats
def profile_code():
# 你的代码
pass
profiler = cProfile.Profile()
profiler.enable()
profile_code()
profiler.disable()
stats = pstats.Stats(profiler).sort_stats('cumulative')
stats.print_stats()
常见问题与解决方案
死锁(Deadlock)
死锁是指两个或多个线程互相等待对方释放资源,导致它们都无法继续执行。为了避免死锁,尽量避免嵌套锁的使用,或者使用 try...finally 语句确保锁总是会被释放。
lock1 = threading.Lock()
lock2 = threading.Lock()
def thread1():
with lock1:
time.sleep(1)
with lock2:
print("Thread 1 done")
def thread2():
with lock2:
time.sleep(1)
with lock1:
print("Thread 2 done")
# 这种情况下可能会发生死锁
t1 = threading.Thread(target=thread1)
t2 = threading.Thread(target=thread2)
t1.start()
t2.start()
t1.join()
t2.join()
活锁(Livelock)
活锁是指线程不断重复尝试执行某个操作,但由于条件始终不满足,导致它们无法继续前进。为了避免活锁,可以在每次尝试失败后引入随机延迟,或者使用超时机制。
import random
def livelock_example():
while True:
if not can_acquire_lock():
time.sleep(random.random()) # 随机延迟
else:
break
线程饥饿(Thread Starvation)
线程饥饿是指某些线程由于优先级较低或其他原因,长期无法获得 CPU 时间。为了避免线程饥饿,可以使用公平锁(Fair Lock),或者确保高优先级线程不会长时间占用资源。
from threading import Lock
fair_lock = Lock()
def fair_thread():
with fair_lock:
print("Fair thread acquired the lock")
线程安全的第三方库一些第三方库提供了线程安全的功能,例如 requests.Session、pandas.DataFrame 等。在使用这些库时,确保了解它们的线程安全性,避免不必要的锁竞争。
实战案例
网络爬虫中的多线程应用
网络爬虫通常需要从多个网站抓取数据,这是一个典型的 I/O 密集型任务。使用多线程可以显著提高爬虫的效率。
import requests
from concurrent.futures import ThreadPoolExecutor
def fetch_url(url):
response = requests.get(url)
return response.text
喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。
相关推荐
- 了解Linux目录,那你就了解了一半的Linux系统
-
大到公司或者社群再小到个人要利用Linux来开发产品的人实在是多如牛毛,每个人都用自己的标准来配置文件或者设置目录,那么未来的Linux则就是一团乱麻,也对管理造成许多麻烦。后来,就有所谓的FHS(F...
- Linux命令,这些操作要注意!(linux命令?)
-
刚玩Linux的人总觉得自己在演黑客电影,直到手滑输错命令把公司服务器删库,这才发现命令行根本不是随便乱用的,而是“生死簿”。今天直接上干货,告诉你哪些命令用好了封神!喜欢的一键三连,谢谢观众老爷!!...
- Linux 命令速查手册:这 30 个高频指令,拯救 90% 的运维小白!
-
在Linux系统的世界里,命令行是强大的武器。对于运维小白而言,掌握一些高频使用的Linux命令,能极大提升工作效率,轻松应对各种系统管理任务。今天,就为大家奉上精心整理的30个Linu...
- linux必学的60个命令(linux必学的20个命令)
-
以下是Linux必学的20个基础命令:1.cd:切换目录2.ls:列出文件和目录3.mkdir:创建目录4.rm:删除文件或目录5.cp:复制文件或目录6.mv:移动/重命名文件或目录7....
- 提高工作效率的--Linux常用命令,能够决解95%以上的问题
-
点击上方关注,第一时间接受干货转发,点赞,收藏,不如一次关注评论区第一条注意查看回复:Linux命令获取linux常用命令大全pdf+Linux命令行大全pdf为什么要学习Linux命令?1、因为Li...
- 15 个实用 Linux 命令(linux命令用法及举例)
-
Linux命令行是系统管理员、开发者和技术爱好者的强大工具。掌握实用命令不仅能提高效率,还能解锁Linux系统的无限潜力,本文将深入介绍15个实用Linux命令。ls-列出目录内容l...
- Linux 常用命令集合(linux常用命令全集)
-
系统信息arch显示机器的处理器架构(1)uname-m显示机器的处理器架构(2)uname-r显示正在使用的内核版本dmidecode-q显示硬件系统部件-(SMBIOS/DM...
- Linux的常用命令就是记不住,怎么办?
-
1.帮助命令1.1help命令#语法格式:命令--help#作用:查看某个命令的帮助信息#示例:#ls--help查看ls命令的帮助信息#netst...
- Linux常用文件操作命令(linux常用文件操作命令有哪些)
-
ls命令在Linux维护工作中,经常使用ls这个命令,这是最基本的命令,来写几条常用的ls命令。先来查看一下使用的ls版本#ls--versionls(GNUcoreutils)8.4...
- Linux 常用命令(linux常用命令)
-
日志排查类操作命令查看日志cat/var/log/messages、tail-fxxx.log搜索关键词grep"error"xxx.log多条件过滤`grep-E...
- 简单粗暴收藏版:Linux常用命令大汇总
-
号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友在Linux系统中,命令行界面(CLI)是管理员和开发人员最常用的工具之一。通过命令行,用户可...
- 「Linux」linux常用基本命令(linux常用基本命令和用法)
-
Linux中许多常用命令是必须掌握的,这里将我学linux入门时学的一些常用的基本命令分享给大家一下,希望可以帮助你们。总结送免费学习资料(包含视频、技术学习路线图谱、文档等)1、显示日期的指令:d...
- Linux的常用命令就是记不住,怎么办?于是推出了这套教程
-
1.帮助命令1.1help命令#语法格式:命令--help#作用:查看某个命令的帮助信息#示例:#ls--help查看ls命令的帮助信息#netst...
- Linux的30个常用命令汇总,运维大神必掌握技能!
-
以下是Linux系统中最常用的30个命令,精简版覆盖日常操作核心需求,适合快速掌握:一、文件/目录操作1.`ls`-列出目录内容`ls-l`(详细信息)|`ls-a`(显示隐藏文件)...
- Linux/Unix 系统中非常常用的命令
-
Linux/Unix系统中非常常用的命令,它们是进行文件操作、文本处理、权限管理等任务的基础。下面是对这些命令的简要说明:**文件操作类:*****`ls`(list):**列出目录内容,显...
- 一周热门
- 最近发表
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- resize函数 (64)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- mybatis大于等于 (64)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- logstashinput (65)
- hadoop端口 (65)
- vue阻止冒泡 (67)
- oracle时间戳转换日期 (64)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)