Python 多线程编程:提升程序运行效率的代码

部署运行你感兴趣的模型镜像

Python 多线程编程的核心方法

使用 threading 模块创建线程
通过继承 threading.Thread 类或直接调用 threading.Thread(target=函数名) 创建线程。示例代码:

import threading

def task():
    print("线程执行的任务")

# 方法1:直接传入函数
thread = threading.Thread(target=task)
thread.start()

# 方法2:继承Thread类
class MyThread(threading.Thread):
    def run(self):
        print("子类线程执行的任务")

my_thread = MyThread()
my_thread.start()

线程同步与锁机制
多线程共享数据时需使用锁(Lock)避免竞争条件。示例:

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    with lock:  # 自动获取和释放锁
        counter += 1

threads = []
for _ in range(10):
    t = threading.Thread(target=increment)
    threads.append(t)
    t.start()

for t in threads:
    t.join()
print(f"最终计数器值: {counter}")

线程池优化资源管理
使用 concurrent.futures.ThreadPoolExecutor 高效管理线程生命周期:

from concurrent.futures import ThreadPoolExecutor

def task(n):
    return n * n

with ThreadPoolExecutor(max_workers=3) as executor:
    results = executor.map(task, [1, 2, 3, 4])
    for result in results:
        print(result)

实际应用场景示例

IO 密集型任务加速
多线程适合网络请求、文件读写等等待操作:

import threading
import requests

def fetch_url(url):
    response = requests.get(url)
    print(f"{url} 响应长度: {len(response.text)}")

urls = ["https://example.com", "https://python.org"]
threads = []
for url in urls:
    t = threading.Thread(target=fetch_url, args=(url,))
    t.start()
    threads.append(t)

for t in threads:
    t.join()

GIL 限制与替代方案
Python 的全局解释器锁(GIL)限制多线程的 CPU 并行能力。CPU 密集型任务可改用 multiprocessing 模块:

from multiprocessing import Pool

def compute(n):
    return n ** 2

if __name__ == "__main__":
    with Pool(4) as p:
        print(p.map(compute, [1, 2, 3]))

调试与性能分析

线程安全日志记录
使用 logging 模块确保日志输出不乱序:

import logging
import threading

logging.basicConfig(level=logging.INFO, format='%(threadName)s: %(message)s')

def worker():
    logging.info("线程执行中")

threads = []
for i in range(3):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()

性能对比工具
通过 time 模块测量多线程与单线程耗时差异:

import time
import threading

def single_thread():
    for _ in range(3):
        time.sleep(1)

def multi_thread():
    threads = []
    for _ in range(3):
        t = threading.Thread(target=lambda: time.sleep(1))
        threads.append(t)
        t.start()
    for t in threads:
        t.join()

start = time.time()
single_thread()
print(f"单线程耗时: {time.time() - start:.2f}s")

start = time.time()
multi_thread()
print(f"多线程耗时: {time.time() - start:.2f}s")

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值