百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python启航:30天编程速成之旅(第23天)- 多线程从入门到精通

off999 2024-12-29 05:05 31 浏览 0 评论

喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。

前期基础教程:

「Python3.11.0」手把手教你安装最新版Python运行环境

讲讲Python环境使用Pip命令快速下载各类库的方法

Python启航:30天编程速成之旅(第2天)-IDE安装

【Python教程】JupyterLab 开发环境安装


Python启航:30天编程速成之旅(第23天)- 多线程从入门到精通

简介

什么是多线程?

多线程是指一个程序中可以同时运行多个线程。每个线程是程序的一个独立执行路径,可以并行执行任务。多线程允许多个任务在同一个进程中并发执行,从而提高程序的效率和响应速度。

为什么使用多线程?

  1. 提高程序的响应性:例如,在 GUI 应用中,主线程负责处理用户界面,而其他线程可以执行后台任务,确保用户界面不会因为长时间的任务而卡住。
  2. 充分利用多核 CPU:虽然 Python 的 GIL 限制了多线程在 CPU 密集型任务中的并行性,但对于 I/O 密集型任务(如网络请求、文件读写),多线程可以显著提高性能。
  3. 简化代码结构:通过将复杂的任务分解为多个线程,可以使代码更易于理解和维护。

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:设置线程是否为守护线程。守护线程会在主线程结束时自动终止。

线程的生命周期

线程的生命周期包括以下几个阶段:

  1. 新建:线程对象被创建,但尚未启动。
  2. 就绪:线程已经启动,等待调度器分配 CPU 时间。
  3. 运行:线程正在执行。
  4. 阻塞:线程暂时停止执行,等待某个条件(如 I/O 操作完成)。
  5. 死亡:线程执行完毕或被终止。

中级:线程同步与通信

当多个线程同时访问共享资源时,可能会导致数据不一致或竞争条件(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

喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。

相关推荐

阿里云国际站ECS:阿里云ECS如何提高网站的访问速度?

TG:@yunlaoda360引言:速度即体验,速度即业务在当今数字化的世界中,网站的访问速度已成为决定用户体验、用户留存乃至业务转化率的关键因素。页面加载每延迟一秒,都可能导致用户流失和收入损失。对...

高流量大并发Linux TCP性能调优_linux 高并发网络编程

其实主要是手里面的跑openvpn服务器。因为并没有明文禁p2p(哎……想想那么多流量好像不跑点p2p也跑不完),所以造成有的时候如果有比较多人跑BT的话,会造成VPN速度急剧下降。本文所面对的情况为...

性能测试100集(12)性能指标资源使用率

在性能测试中,资源使用率是评估系统硬件效率的关键指标,主要包括以下四类:#性能测试##性能压测策略##软件测试#1.CPU使用率定义:CPU处理任务的时间占比,计算公式为1-空闲时间/总...

Linux 服务器常见的性能调优_linux高性能服务端编程

一、Linux服务器性能调优第一步——先搞懂“看什么”很多人刚接触Linux性能调优时,总想着直接改配置,其实第一步该是“看清楚问题”。就像医生看病要先听诊,调优前得先知道服务器“哪里...

Nginx性能优化实战:手把手教你提升10倍性能!

关注△mikechen△,十余年BAT架构经验倾囊相授!Nginx是大型架构而核心,下面我重点详解Nginx性能@mikechen文章来源:mikechen.cc1.worker_processe...

高并发场景下,Spring Cloud Gateway如何抗住百万QPS?

关注△mikechen△,十余年BAT架构经验倾囊相授!大家好,我是mikechen。高并发场景下网关作为流量的入口非常重要,下面我重点详解SpringCloudGateway如何抗住百万性能@m...

Kubernetes 高并发处理实战(可落地案例 + 源码)

目标场景:对外提供HTTPAPI的微服务在短时间内收到大量请求(例如每秒数千至数万RPS),要求系统可弹性扩容、限流降级、缓存减压、稳定运行并能自动恢复。总体思路(多层防护):边缘层:云LB...

高并发场景下,Nginx如何扛住千万级请求?

Nginx是大型架构的必备中间件,下面我重点详解Nginx如何实现高并发@mikechen文章来源:mikechen.cc事件驱动模型Nginx采用事件驱动模型,这是Nginx高并发性能的基石。传统...

Spring Boot+Vue全栈开发实战,中文版高清PDF资源

SpringBoot+Vue全栈开发实战,中文高清PDF资源,需要的可以私我:)SpringBoot致力于简化开发配置并为企业级开发提供一系列非业务性功能,而Vue则采用数据驱动视图的方式将程序...

Docker-基础操作_docker基础实战教程二

一、镜像1、从仓库获取镜像搜索镜像:dockersearchimage_name搜索结果过滤:是否官方:dockersearch--filter="is-offical=true...

你有空吗?跟我一起搭个服务器好不好?

来人人都是产品经理【起点学院】,BAT实战派产品总监手把手系统带你学产品、学运营。昨天闲的没事的时候,随手翻了翻写过的文章,发现一个很严重的问题。就是大多数时间我都在滔滔不绝的讲理论,却很少有涉及动手...

部署你自己的 SaaS_saas如何部署

部署你自己的VPNOpenVPN——功能齐全的开源VPN解决方案。(DigitalOcean教程)dockovpn.io—无状态OpenVPNdockerized服务器,不需要持久存储。...

Docker Compose_dockercompose安装

DockerCompose概述DockerCompose是一个用来定义和管理多容器应用的工具,通过一个docker-compose.yml文件,用YAML格式描述服务、网络、卷等内容,...

京东T7架构师推出的电子版SpringBoot,从构建小系统到架构大系统

前言:Java的各种开发框架发展了很多年,影响了一代又一代的程序员,现在无论是程序员,还是架构师,使用这些开发框架都面临着两方面的挑战。一方面是要快速开发出系统,这就要求使用的开发框架尽量简单,无论...

Kubernetes (k8s) 入门学习指南_k8s kubeproxy

Kubernetes(k8s)入门学习指南一、什么是Kubernetes?为什么需要它?Kubernetes(k8s)是一个开源的容器编排系统,用于自动化部署、扩展和管理容器化应用程序。它...

取消回复欢迎 发表评论: