< 笔记 > Python

来源:互联网 发布:mysql 格式化时间戳 编辑:程序博客网 时间:2024/05/29 17:39

11 Python 进程和线程

By Kevin Song

  • 11-01 多进程
  • 11-02 多线程
  • 11-03 ThreadLocal
  • 11-04 进程vs线程
  • 11-05 分布式进程

进程(Process):操作系统中执行的任务

线程(Thread):每个任务需要同时处理子任务

Python执行多任务解决方案

  • 多进程:多个进程,每个进程运行一个线程
  • 多线程:一个进程,这个进程运行多个线程
  • 多进程+多线程:多个进程,每个进程运行多个线程(模型复杂,很少采用)

多进程和多线程的区别:

  • 多进程:同一个变量,各自有一份拷贝存在于每个进程中,互不影响
  • 多线程:所有变量都由所有线程共享,任何一个变量都可以被任何一个线程修改

11-01 多进程(Multiprocessing)

Unix/Linux

Unix/Linux操作系统提供了一个 fork() 系统调用,fork()调用一次,返回两次,操作系统自动把当前进程(父进程)复制了一份(子进程),然后,分别在父进程和子进程内返回

  • 子进程返回0
  • 父进程返回子进程的ID:os.getpid()
  • 父进程的ID:getppid()
import osprint('Process (%s) start...' % os.getpid())# Only works on Unix/Linux/Mac:pid = os.fork()if pid == 0:    print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))else:    print('I (%s) just created a child process (%s).' % (os.getpid(), pid))
Process (876) start...I (876) just created a child process (877).I am child process (877) and my parent is 876.

Windows

multiprocessing模块提供了一个Process类来代表一个进程对象

from multiprocessing import Processimport os# 子进程要执行的代码def run_proc(name):    print('Run child process %s (%s)...' % (name, os.getpid()))if __name__=='__main__':    print('Parent process %s.' % os.getpid())    p = Process(target=run_proc, args=('test',))    print('Child process will start.')    p.start()    p.join()    print('Child process end.')
Parent process 928.Process will start.Run child process test (929)...Process end.

创建子进程方式:p = Process(target=run_proc, args=(‘test’,))

  1. 创建一个Process实例
  2. 传入一个执行函数和函数的参数
  3. start()启动
  4. join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步

Pool:批量创建子进程

用进程池批量创建子进程:

from multiprocessing import Poolimport os, time, randomdef long_time_task(name):    print('Run task %s (%s)...' % (name, os.getpid()))    start = time.time()    time.sleep(random.random() * 3)    end = time.time()    print('Task %s runs %0.2f seconds.' % (name, (end - start)))if __name__=='__main__':    print('Parent process %s.' % os.getpid())    p = Pool(4)    for i in range(5):        p.apply_async(long_time_task, args=(i,))    print('Waiting for all subprocesses done...')    p.close()    p.join()    print('All subprocesses done.')
Parent process 669.Waiting for all subprocesses done...Run task 0 (671)...Run task 1 (672)...Run task 2 (673)...Run task 3 (674)...Task 2 runs 0.14 seconds.Run task 4 (673)...Task 1 runs 0.27 seconds.Task 3 runs 0.86 seconds.Task 0 runs 1.41 seconds.Task 4 runs 1.91 seconds.All subprocesses done.

对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了

子进程

用subprocess模块 启动 并且 控制 子进程的 输入输出

运行命令nslookup www.python.org

import subprocessprint('$ nslookup www.python.org')r = subprocess.call(['nslookup', 'www.python.org'])print('Exit code:', r)

运行结果:

$ nslookup www.python.orgServer:        192.168.19.4Address:    192.168.19.4#53Non-authoritative answer:www.python.org    canonical name = python.map.fastly.net.Name:    python.map.fastly.netAddress: 199.27.79.223Exit code: 0

communicate()方法输入:

import subprocessprint('$ nslookup')p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)output, err = p.communicate(b'set q=mx\npython.org\nexit\n')print(output.decode('utf-8'))print('Exit code:', p.returncode)

运行结果:

$ nslookupServer:        192.168.19.4Address:    192.168.19.4#53Non-authoritative answer:python.org    mail exchanger = 50 mail.python.org.Authoritative answers can be found from:mail.python.org    internet address = 82.94.164.166mail.python.org    has AAAA address 2001:888:2000:d::a6Exit code: 0

进程间通信

multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据

父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:

from multiprocessing import Process, Queueimport os, time, random# 写数据进程执行的代码:def write(q):    print('Process to write: %s' % os.getpid())    for value in ['A', 'B', 'C']:        print('Put %s to queue...' % value)        q.put(value)        time.sleep(random.random())# 读数据进程执行的代码:def read(q):    print('Process to read: %s' % os.getpid())    while True:        value = q.get(True)        print('Get %s from queue.' % value)if __name__=='__main__':    # 父进程创建Queue,并传给各个子进程:    q = Queue()    pw = Process(target=write, args=(q,))    pr = Process(target=read, args=(q,))    # 启动子进程pw,写入:    pw.start()    # 启动子进程pr,读取:    pr.start()    # 等待pw结束:    pw.join()    # pr进程里是死循环,无法等待其结束,只能强行终止:    pr.terminate()
Process to write: 50563Put A to queue...Process to read: 50564Get A from queue.Put B to queue...Get B from queue.Put C to queue...Get C from queue.

11-02 多线程

一个进程里的多个线程实现多任务

Python的标准库提供了两个模块

  • _thread(低级模块)
  • threading(高级模块):对_thread进行了封装

启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:

格式:

t = threading.Thread(target='需要运行的方法名', args=('方法参数,'), name='自定义线程名称')t.start()t.join()

示例:

import time, threading# 新线程执行的代码:def loop():    print('thread %s is running...' % threading.current_thread().name)    n = 0    while n < 5:        n = n + 1        print('thread %s >>> %s' % (threading.current_thread().name, n))        time.sleep(1)    print('thread %s ended.' % threading.current_thread().name)print('thread %s is running...' % threading.current_thread().name)t = threading.Thread(target=loop, name='LoopThread')t.start()t.join()print('thread %s ended.' % threading.current_thread().name)
thread MainThread is running...thread LoopThread is running...thread LoopThread >>> 1thread LoopThread >>> 2thread LoopThread >>> 3thread LoopThread >>> 4thread LoopThread >>> 5thread LoopThread ended.thread MainThread ended.
  • threading 模块
    • threading.current_thread():返回当前线程实例
      • threading.current_thread().name:返回当前线程实例的name

Lock

不加Lock的多线程在操作同一数据时会把数据改乱

import time, threading# 假定这是你的银行存款:balance = 0def change_it(n):    # 先存后取,结果应该为0:    global balance    balance = balance + n    balance = balance - ndef run_thread(n):    for i in range(100000):        change_it(n)t1 = threading.Thread(target=run_thread, args=(5,))t2 = threading.Thread(target=run_thread, args=(8,))t1.start()t2.start()t1.join()t2.join()print(balance)

数据改乱根本原因:

  • 线程交替运行
  • 操作同一变量(balance)
初始值 balance = 0t1: x1 = balance + 5  # x1 = 0 + 5 = 5t2: x2 = balance + 8  # x2 = 0 + 8 = 8t2: balance = x2      # balance = 8t1: balance = x1      # balance = 5t1: x1 = balance - 5  # x1 = 5 - 5 = 0t1: balance = x1      # balance = 0t2: x2 = balance - 8  # x2 = 0 - 8 = -8t2: balance = x2   # balance = -8结果 balance = -8

threading.Lock(): 拿到锁的线程才可以运行方法

balance = 0lock = threading.Lock()def run_thread(n):    for i in range(100000):        # 先要获取锁:        lock.acquire()        try:            # 放心地改吧:            change_it(n)        finally:            # 改完了一定要释放锁:            lock.release()
  • lock.acquire()获取锁
  • 用try-finally确保锁一定可以释放,否则造成死锁

多核CPU

  • 多核CPU中,一个死循环线程会导致100%占用一个CPU
  • 两个死循环线程,在多核CPU中,可以监控到会占用200%的CPU
  • 以此类推

死循环示例

import threading, multiprocessingdef loop():    x = 0    while True:        x = x ^ 1for i in range(multiprocessing.cpu_count()):    t = threading.Thread(target=loop)    t.start()
  • C、C++或Java来改写相同的死循环,直接可以把全部核心跑满,4核就跑到400%,8核就跑到800%
  • Python最多102%
    • 解释器执行代码时,有一个GIL锁:Global Interpreter Lock。任何Python线程执行前,必须先获得GIL锁,然后,每执行100条字节码,解释器就自动释放GIL锁,让别的线程有机会执行。

所以,多线程在Python中只能交替执行,即使100个线程跑在100核CPU上,也只能用到1个核

11-03 ThreadLocal

局部变量优点:全局变量的修改必须加锁,因此一个线程使用自己的局部变量比使用全局变量好

局部变量缺点:函数调用的时候,传递起来很麻烦,如下

def process_student(name):    std = Student(name)    # std是局部变量,但是每个函数都要用它,因此必须传进去:    do_task_1(std)    do_task_2(std)def do_task_1(std):    do_subtask_1(std)    do_subtask_2(std)def do_task_2(std):    do_subtask_2(std)    do_subtask_2(std)

解决方案:ThreadLocal

import threading# 创建全局ThreadLocal对象:local_school = threading.local()def process_student():    # 获取当前线程关联的student:    std = local_school.student    print('Hello, %s (in %s)' % (std, threading.current_thread().name))def process_thread(name):    # 绑定ThreadLocal的student:    local_school.student = name    process_student()t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A')t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')t1.start()t2.start()t1.join()t2.join()
Hello, Alice (in Thread-A)Hello, Bob (in Thread-B)

全局变量local_school就是一个ThreadLocal对象。Thread对它都可以读写student属性,但互不影响。

  • local_school相当于全局变量
  • local_school.student都是线程的局部变量

11-04 进程vs线程

Master-Worker模式

  • Master负责分配任务(一)
  • Worker负责执行任务(多)

实现Master-Worker

  • 多进程实现Master-Worker,主进程就是Master,其他进程就是Worker
  • 多线程实现Master-Worker,主线程就是Master,其他线程就是Worker

优缺点

  • 多进程

    • 优点:稳定性高
      • 子进程崩溃了不会影响主进程和其他子进程
    • 缺点:创建代价大
      • Unix/Linux系统下用fork调用还行
      • Windows下创建进程开销巨大
      • 操作系统能同时运行的进程数也是有限
  • 多线程

    • 优点:速度比多进程快(只快一点点)
    • 缺点:稳定性差
      • 一个线程挂掉都可能直接造成整个进程崩溃

线程切换

单任务模型(批处理任务模型)

  • 处理完 A任务 处理 B任务
  • 处理完 B任务 处理 C任务
  • 处理完 C任务 结束

多任务模型

  • 处理 A任务 1秒
    • 保存现场:保存 A任务 CPU寄存器状态、内存页等
    • 准备新环境:恢复 B任务 的寄存器状态,切换内存页等
  • 处理 B任务 1秒
    • 保存现场:保存 B任务 CPU寄存器状态、内存页等
    • 准备新环境:恢复 C任务 的寄存器状态,切换内存页等
  • 处理 C任务 1秒
    • 保存现场:保存 C任务 CPU寄存器状态、内存页等
    • 准备新环境:恢复 B任务 的寄存器状态,切换内存页等
  • 处理 B任务 1秒

切换过程虽然很快,但需要耗费时间。如果有几千个任务同时进行,操作系统可能就主要忙着切换任务,根本没有多少时间去执行任务,这种情况最常见的就是硬盘狂响,点窗口无反应,系统处于假死状态

计算密集型 vs. IO密集型

计算密集型任务

  • 进行大量的计算,消耗CPU资源,比如计算圆周率、对视频进行高清解码等等,全靠CPU的运算能力
  • 任务越多,花在任务切换的时间就越多,CPU执行任务的效率就越低
  • 最高效地利用CPU,计算密集型任务同时进行的数量应当等于CPU的核心数
    计算密集型任务由于主要消耗CPU资源,因此,代码运行效率至关重要。Python这样的脚本语言运行效率很低,完全不适合计算密集型任务。对于计算密集型任务,最好用C语言编写。

IO密集型

  • CPU消耗很少,任务的大部分时间都在等待IO操作完成(因为IO的速度远远低于CPU和内存的速度)
  • 任务越多,CPU效率越高,但也有一个限度

IO密集型任务执行期间,99%的时间都花在IO上,花在CPU上的时间很少,因此,用运行速度极快的C语言替换用Python这样运行速度极低的脚本语言,完全无法提升运行效率。对于IO密集型任务,最合适的语言就是开发效率最高(代码量最少)的语言,脚本语言是首选,C语言最差。

异步IO

多进程模型或者多线程模型来支持多任务并发执行

11-05 分布式进程

  • Process更稳定,可以分布到多台机器上
  • Thread最多只能分布到同一台机器的多个CPU上

Python的multiprocessing模块的managers子模块支持把多进程分布到多台机器上。一个服务进程可以作为调度者,将任务分布到其他多个进程中,依靠网络通信

服务进程负责启动Queue,把Queue注册到网络上,然后往Queue里面写入任务:

# task_master.pyimport random, time, queuefrom multiprocessing.managers import BaseManager# 发送任务的队列:task_queue = queue.Queue()# 接收结果的队列:result_queue = queue.Queue()# 从BaseManager继承的QueueManager:class QueueManager(BaseManager):    pass# 把两个Queue都注册到网络上, callable参数关联了Queue对象:QueueManager.register('get_task_queue', callable=lambda: task_queue)QueueManager.register('get_result_queue', callable=lambda: result_queue)# 绑定端口5000, 设置验证码'abc':manager = QueueManager(address=('', 5000), authkey=b'abc')# 启动Queue:manager.start()# 获得通过网络访问的Queue对象:task = manager.get_task_queue()result = manager.get_result_queue()# 放几个任务进去:for i in range(10):    n = random.randint(0, 10000)    print('Put task %d...' % n)    task.put(n)# 从result队列读取结果:print('Try get results...')for i in range(10):    r = result.get(timeout=10)    print('Result: %s' % r)# 关闭:manager.shutdown()print('master exit.')

另一台机器上启动任务进程(本机上启动也可以):

# task_worker.pyimport time, sys, queuefrom multiprocessing.managers import BaseManager# 创建类似的QueueManager:class QueueManager(BaseManager):    pass# 由于这个QueueManager只从网络上获取Queue,所以注册时只提供名字:QueueManager.register('get_task_queue')QueueManager.register('get_result_queue')# 连接到服务器,也就是运行task_master.py的机器:server_addr = '127.0.0.1'print('Connect to server %s...' % server_addr)# 端口和验证码注意保持与task_master.py设置的完全一致:m = QueueManager(address=(server_addr, 5000), authkey=b'abc')# 从网络连接:m.connect()# 获取Queue的对象:task = m.get_task_queue()result = m.get_result_queue()# 从task队列取任务,并把结果写入result队列:for i in range(10):    try:        n = task.get(timeout=1)        print('run task %d * %d...' % (n, n))        r = '%d * %d = %d' % (n, n, n*n)        time.sleep(1)        result.put(r)    except Queue.Empty:        print('task queue is empty.')# 处理结束:print('worker exit.')

启动task_master.py服务进程:

$ python3 task_master.py Put task 3411...Put task 1605...Put task 1398...Put task 4729...Put task 5300...Put task 7471...Put task 68...Put task 4219...Put task 339...Put task 7866...Try get results...

task_master.py进程发送完任务后,开始等待result队列的结果。现在启动task_worker.py进程:

$ python3 task_worker.pyConnect to server 127.0.0.1...run task 3411 * 3411...run task 1605 * 1605...run task 1398 * 1398...run task 4729 * 4729...run task 5300 * 5300...run task 7471 * 7471...run task 68 * 68...run task 4219 * 4219...run task 339 * 339...run task 7866 * 7866...worker exit.

这就是一个简单但真正的分布式计算

Queue对象存储在task_master.py进程中

而Queue之所以能通过网络访问,就是通过QueueManager实现的。由于QueueManager管理的不止一个Queue,所以,要给每个Queue的网络调用接口起个名字,比如get_task_queue。

authkey有什么用?这是为了保证两台机器正常通信,不被其他机器恶意干扰。如果task_worker.py的authkey和task_master.py的authkey不一致,肯定连接不上。

原创粉丝点击