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

Python并发编程实用教程

ztj100 2025-05-26 20:19 23 浏览 0 评论

#Python知识分享#

一、并发编程基础

1. 并发与并行概念

定义对比

  • 并发:交替执行任务(单核)
  • 并行:同时执行任务(多核)

并发vs并行示意图

并发: [任务A] <-> [任务B] <-> [任务A] <-> [任务B] (时间切片)
并行: [任务A] → 同时执行 ← [任务B] (多核)

表1 Python并发编程方式对比

方式

模块

适用场景

特点

多线程

threading

I/O密集型

共享内存,GIL限制

多进程

multiprocessing

CPU密集型

独立内存,开销大

协程

asyncio

高并发I/O

单线程异步,高效


二、多线程编程

1. Thread类基础

语法定义

from threading import Thread

t = Thread(target=函数, args=(参数,))
t.start()
t.join()

应用示例

import time
from threading import Thread

def download_file(url):
    print(f"开始下载 {url}")
    time.sleep(2)  # 模拟I/O操作
    print(f"完成下载 {url}")

# 创建并启动线程
threads = []
for i in range(3):
    t = Thread(target=download_file, args=(f"https://example.com/file{i}.zip",))
    threads.append(t)
    t.start()

# 等待所有线程完成
for t in threads:
    t.join()

print("所有下载任务完成")

注意事项

  • 线程适合I/O密集型任务
  • 受GIL限制,不适合CPU密集型任务
  • 注意线程安全问题

三、多进程编程

1. Process类使用

语法定义

from multiprocessing import Process

p = Process(target=函数, args=(参数,))
p.start()
p.join()

应用示例

import math
from multiprocessing import Process

def calculate_factorial(n):
    print(f"计算 {n} 的阶乘")
    result = math.factorial(n)
    print(f"{n}! = {result}")

if __name__ == '__main__':
    numbers = [1000, 2000, 3000]
    processes = []

    for num in numbers:
        p = Process(target=calculate_factorial, args=(num,))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()

    print("所有计算完成")

多进程内存模型

进程A ── 独立内存空间
进程B ── 独立内存空间
进程C ── 独立内存空间

四、异步编程(asyncio)

1. 协程基础

语法定义

import asyncio

async def 协程函数():
    await 异步操作

asyncio.run(协程函数())

应用示例

import asyncio

async def fetch_data(url):
    print(f"开始获取 {url}")
    await asyncio.sleep(2)  # 模拟I/O等待
    print(f"完成获取 {url}")
    return f"{url} 的数据"

async def main():
    tasks = [
        fetch_data("https://api.com/data1"),
        fetch_data("https://api.com/data2"),
        fetch_data("https://api.com/data3")
    ]
    results = await asyncio.gather(*tasks)
    print("所有结果:", results)

asyncio.run(main())

表2 同步vs异步I/O对比

特性

同步I/O

异步I/O

线程使用

阻塞线程

单线程处理

性能

低(串行)

高(并发)

复杂度

简单

需要async/await

适用场景

简单逻辑

高并发网络请求


五、线程/进程池

1. ThreadPoolExecutor

语法定义

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=5) as executor:
    future = executor.submit(函数, 参数)
    result = future.result()

应用示例

from concurrent.futures import ThreadPoolExecutor
import urllib.request

def download(url):
    with urllib.request.urlopen(url) as response:
        return f"{url}: {len(response.read())} bytes"

urls = [
    "https://www.python.org",
    "https://www.google.com",
    "https://www.github.com"
]

with ThreadPoolExecutor(max_workers=3) as executor:
    futures = [executor.submit(download, url) for url in urls]
    for future in futures:
        print(future.result())

2. ProcessPoolExecutor

语法定义

from concurrent.futures import ProcessPoolExecutor

with ProcessPoolExecutor(max_workers=4) as executor:
    future = executor.submit(函数, 参数)
    result = future.result()

应用示例

from concurrent.futures import ProcessPoolExecutor
import math

def compute_factorial(n):
    return math.factorial(n)

numbers = [1000, 2000, 3000, 4000]

with ProcessPoolExecutor() as executor:
    results = executor.map(compute_factorial, numbers)
    for num, result in zip(numbers, results):
        print(f"{num}! 的计算完成")

六、共享数据与同步

1. 线程安全操作

表3 线程同步原语

工具

用途

示例

Lock

互斥锁

with lock:

RLock

可重入锁

with rlock:

Semaphore

信号量

semaphore.acquire()

Queue

线程安全队列

queue.put/get()

应用示例

from threading import Thread, Lock
import time

class BankAccount:
    def __init__(self):
        self.balance = 100
        self.lock = Lock()
    
    def deposit(self, amount):
        with self.lock:
            new_balance = self.balance + amount
            time.sleep(0.1)  # 模拟处理延迟
            self.balance = new_balance

account = BankAccount()
threads = []

for _ in range(10):
    t = Thread(target=account.deposit, args=(10,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print(f"最终余额: {account.balance}")  # 正确结果200

七、应用案例

1. 并发Web爬虫示例

import asyncio
import aiohttp
from concurrent.futures import ThreadPoolExecutor

async def fetch_url(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
        "https://www.python.org",
        "https://www.google.com",
        "https://www.github.com"
    ]
    
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        for url, content in zip(urls, results):
            print(f"{url}: {len(content)} bytes")

asyncio.run(main())

2. 并行数据处理示例

from multiprocessing import Pool
import pandas as pd

def process_chunk(chunk):
    # 模拟耗时数据处理
    return chunk.describe()

if __name__ == '__main__':
    data = pd.DataFrame({'value': range(1000000)})
    chunks = [data[i:i+100000] for i in range(0, len(data), 100000)]
    
    with Pool(4) as pool:
        results = pool.map(process_chunk, chunks)
    
    final_result = pd.concat(results)
    print(final_result)

八、并发编程建议

  1. I/O密集型:使用线程或异步
  2. CPU密集型:使用多进程
  3. 避免共享状态,使用消息传递
  4. 合理设置工作线程/进程数量
  5. 使用连接池管理资源

表4 并发问题

问题

解决方案

竞态条件

使用Lock/RLock

死锁

避免嵌套锁,设置超时

资源耗尽

使用连接池,限制并发数

GIL限制

使用多进程或C扩展

总结

核心知识点

  1. 多线程适合I/O密集型任务(threading)
  2. 多进程适合CPU密集型任务(multiprocessing)
  3. 协程实现高效I/O并发(asyncio)
  4. 线程/进程池简化资源管理(concurrent.futures)

选择指南

I/O密集型 → 多线程/协程
CPU密集型 → 多进程
高并发网络 → 异步编程
批量计算 → 进程池

Python并发编程决策树

开始 → CPU密集型? → 是 → multiprocessing
            ↓否
          I/O高并发? → 是 → asyncio
            ↓否
          threading/concurrent.futures

持续更新Python编程学习日志与技巧,敬请关注!


#编程# #python# #在头条记录我的2025#


相关推荐

10条军规:电商API从数据泄露到高可用的全链路防护

电商API接口避坑指南:数据安全、版本兼容与成本控制的10个教训在电商行业数字化转型中,API接口已成为连接平台、商家、用户与第三方服务的核心枢纽。然而,从数据泄露到版本冲突,从成本超支到系统崩溃,A...

Python 文件处理在实际项目中的困难与应对策略

在Python项目开发,文件处理是一项基础且关键的任务。然而,在实际项目中,Python文件处理往往会面临各种各样的困难和挑战,从文件格式兼容性、编码问题,到性能瓶颈、并发访问冲突等。本文将深入...

The Future of Manufacturing with Custom CNC Parts

ThefutureofmanufacturingisincreasinglybeingshapedbytheintegrationofcustomCNC(ComputerNumericalContro...

Innovative Solutions in Custom CNC Machining

Inrecentyears,thelandscapeofcustomCNCmachininghasevolvedrapidly,drivenbyincreasingdemandsforprecisio...

C#.NET serilog 详解(c# repository)

简介Serilog是...

Custom CNC Machining for Small Batch Production

Inmodernmanufacturing,producingsmallbatchesofcustomizedpartshasbecomeanincreasinglycommondemandacros...

Custom CNC Machining for Customized Solutions

Thedemandforcustomizedsolutionsinmanufacturinghasgrownsignificantly,drivenbydiverseindustryneedsandt...

Revolutionizing Manufacturing with Custom CNC Parts

Understandinghowmanufacturingisevolving,especiallythroughtheuseofcustomCNCparts,canseemcomplex.Thisa...

Breaking Boundaries with Custom CNC Parts

BreakingboundarieswithcustomCNCpartsinvolvesexploringhowadvancedmanufacturingtechniquesaretransformi...

Custom CNC Parts for Aerospace Industry

Intherealmofaerospacemanufacturing,precisionandreliabilityareparamount.Thecomponentsthatmakeupaircra...

Cnc machining for custom parts and components

UnderstandingCNCmachiningforcustompartsandcomponentsinvolvesexploringitsprocesses,advantages,andcomm...

洞察宇宙(十八):深入理解C语言内存管理

分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“深入理解C语言内存管理”...

The Art of Crafting Custom CNC Parts

UnderstandingtheprocessofcreatingcustomCNCpartscanoftenbeconfusingforbeginnersandevensomeexperienced...

Tailored Custom CNC Solutions for Automotive

Intheautomotiveindustry,precisionandefficiencyarecrucialforproducinghigh-qualityvehiclecomponents.Ta...

关于WEB服务器(.NET)一些经验累积(一)

以前做过技术支持,把一些遇到的问题累积保存起来,现在发出了。1.问题:未能加载文件或程序集“System.EnterpriseServices.Wrapper.dll”或它的某一个依赖项。拒绝访问。解...

取消回复欢迎 发表评论: