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")

被折叠的 条评论
为什么被折叠?



