Python 多线程与并发实战,系统剖析 threading 模块、线程锁与信号量同步机制、线程池优化以及 GIL 对多线程性能的影响与解决方案。
介绍
- Python 的线程虽然是操作系统的原生线程,但解释器执行代码时,有一个 GIL 锁(
Global Interpreter Lock,全局解释器锁)。任何 Python 线程执行前必须先获取 GIL。在早期的 Python 2 中,解释器按固定执行 100 条字节码(check interval)释放 GIL;自 Python 3.2 起,CPython 改为了基于时间的切换机制(默认切换间隔为 5 毫秒,可通过sys.setswitchinterval()调整)。由于 GIL 的存在,同一进程中同一时刻只有一个线程在执行 Python 字节码,纯计算密集型多线程任务无法利用多核进行并行加速 - GIL 是 Python 解释器设计的历史遗留问题,通常我们用的解释器是官方实现的 CPython,要真正利用多核,除非重写一个不带 GIL 的解释器。所以,在 Python 中,可以使用多线程,但不要指望能有效利用多核
- 协程(Coroutine)
- coroutines 是线性处理的,同一时间只有一个 coroutine 在执行。
- subroutine 是 coroutine 的特例
- subroutine 只返回一次,并且不保存调用别人后不保存状态,相反,coroutine 保存状态,coroutine 可以调用 coroutine,是通过 yield 的方式
- 设计一个支持 subroutine 的语言只需要预分配一个 stack 即可,对应的,要支持 coroutine 的话,就需要预分配多个 stack
- coroutine 有什么用?以 producer 和 consumer 为例,用 coroutines 会相当高效:coroutine 间直接调用即可,无需底层 thread 切换,也不需要经过 OS 的公共资源。
- green thread 是由 vm 管理的,不是 OS 管理的,green threads 是仿真了多线程环境,不依赖与底层的 OS,是运行在 user space 下。
- 在多核处理器下,native thread 可以自动分配到多核去,而 green thread 不行
- java 1.1 中,green thread 是唯一的线程模型,由于 green thread 比 native thread 有很多不足,java 后续版本抛弃了 green thread
- python 中的
eventlet是 green thread
实现
- ThreadLocal 的好处是让线程有了自己的空间,而不用全局共享的,同时又避免了作为参数传来传去。
- multiprocessing
- 多进程比多线程稳定些,因为多线程如果其中一个线程有问题,有可能导致整个进程有问题
- threadpool
threading
官方标准库
threading.Thread 示例
说明:
Python 的 threading 模块有个
current_thread()函数,它永远返回当前线程的实例多线程中,所有变量都由所有线程共享。创建一个锁就是通过
threading.Lock()来实现,使用方法是先lock.acquire(),然后lock.release(),并确保lock.release()是在finally中test_threading.py
# -*- coding: utf-8 -*-
# 创建全局ThreadLocal对象:
import threading
from datetime import datetime
localVal = threading.local()
localVal.val = "Main-Thread"
def print_func():
print(f'{datetime.now()} {localVal.val} in {threading.current_thread().name}')
def main_func(name):
# 赋值
localVal.val = name
print_func()
if __name__ == '__main__':
t1 = threading.Thread(target=main_func, args=('One',), name='Thread-One')
t2 = threading.Thread(target=main_func, args=('Two',), name='Thread-Two')
t1.start()
t2.start()
t1.join()
t2.join()
print(f'{datetime.now()} {localVal.val}')- 执行结果
2017-04-01 11:30:03.366336 One in Thread-One
2017-04-01 11:30:03.366475 Two in Thread-Two
2017-04-01 11:30:03.366545 Main-Thread说明:
threading.local()用来保存一个全局变量,但该全局变量只有在当前线程才能访问localVal.val = name储存一个变量name到当前线程- 如果在
线程A里面再次对localVal.val进行赋值,那么线程A会单独创建内存空间来存储赋值 - 即在不同的线程里面赋值不会相互覆盖
- 如果在
执行命令获取 stdout/stderr
import queue
import subprocess
import threading
import sys
def read_from_stream(stream, output_func, q):
"""
从给定的流中读取数据,并使用指定的函数输出。
"""
result = []
for line in iter(stream.readline, b''):
if line is None:
break
decoded_line = line.decode('utf-8').rstrip() if isinstance(line, bytes) else line.rstrip()
output_func(decoded_line)
result.append(decoded_line)
q.put(result)
def print_stdout(line):
"""
打印标准输出。
"""
print(line)
def print_stderr(line):
"""
打印标准错误输出(到stderr)。
"""
print('stderr', line, file=sys.stderr)
def run_command(command):
"""
运行命令,并启动两个线程来分别监听stdout和stderr。
"""
outq = queue.Queue()
errq = queue.Queue()
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 创建并启动线程
stdout_thread = threading.Thread(target=read_from_stream, args=(process.stdout, print_stdout, outq))
stderr_thread = threading.Thread(target=read_from_stream, args=(process.stderr, print_stderr, errq))
stdout_thread.start()
stderr_thread.start()
# 等待子进程完成
stdout_thread.join(timeout=60)
stderr_thread.join(timeout=60)
# 等待子进程完成
process.wait()
return process.poll(), outq.get(), errq.get()
command = ['ping', '-c', '5', 'xiexianbin.cn']
print(run_command(command))
最近更新
最新评论