美文网首页
python3并发编程基础

python3并发编程基础

作者: CurryCoder | 来源:发表于2019-01-23 22:11 被阅读40次

    1.基本概念

    • 1.串行与并行
      • a.串行:比喻是一个人在同一时间段只能干一件事,如只能吃完饭后再玩手机
      • b.并行:比喻是一个人在同一时间段可以干很多事,如一边吃饭一边玩手机
    • 2.在python中,多线程与协程虽然严格上来说是串行,但是却比一般串行程序执行效率高很多。一般的串行程序,在程序阻塞时,只能干等着,不能做其他事情。比如,开始播放电视剧前,必须看完广告才能观看电视剧,这个等待时间我们却不能做其他的事。这种做法效率很低,不合理。虽然多线程和协程已经很智能,但不够高效,最高效的应该是一心多用,同时做多件事情,这是多进程做的事情。
    • 3.多线程:交替执行,另一种意义上的串行


      多线程.png
    • 4.多线程:并行执行,真正意义上的并发


      多进程.png

    2.单线程VS多线程VS多进程

    开始对比之前,首先定义四种类型的场景: CPU计算密集型、磁盘IO密集型、 网络IO密集型、模拟IO密集型

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Date    : 2019-01-21 09:45:56
    # @Author  : cdl (1217096231@qq.com)
    # @Link    : https://github.com/cdlwhm1217096231/python3_spider
    # @Version : $Id$
    
    """
    线程全局解释器锁(Global Interpreter Lock),即Python为了保证线程安全而采取的独立线程运行的限制,说白了就是一个核只能在同一时间运行一个线程.对于io密集型任务,python的多线程起到作用,但对于cpu密集型任务,python的多线程几乎占不到任何优势,还有可能因为争夺资源而变慢。
    解决办法:多进程或协程(协程也只是单CPU,但是能减小切换代价提升性能).
    """
    # 单线程VS多线程VS多进程
    """
    开始对比之前,首先定义四种类型的场景: CPU计算密集型、磁盘IO密集型、 网络IO密集型、模拟IO密集型
    """
    
    
    # CPU计算密集型
    def count(x=1, y=1):
        # 使程序完成150万计算
        c = 0
        while c < 500000:
            c += 1
            x += x
            y += y
    
    
    #  磁盘读写IO密集型
    def io_disk():
        with open("file.txt", 'w') as f:
            for x in range(500000):
                f.write("python_learning\n")
    
    
    # 网络IO密集型
    import requests
    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
    }
    url = "https://www.tieba.com/"
    
    
    def io_web():
        try:
            response = requests.get(url, header=header)
            html = response.text
        except Exception as e:
            return {"error": e}
    
    
    import time
    # 模拟IO密集型
    
    
    def io_simulation():
        time.sleep(2)
    
    
    # 比较的指标是:时间,时间花费越少,说明效率越高
    from functools import wraps
    
    
    def timer(model):
        def wrapper(func):
            def decorator(*args, **kwargs):
                type = kwargs.setdefault('type', None)
                t1 = time.time()
                func(*args, **kwargs)  # 被装饰函数
                t2 = time.time()
                cost_time = t2 - t1
                print("{}-{}花费时间:{}s".format(model, type, cost_time))
            return decorator
        return wrapper
    
    # 单线程
    # 被装饰函数
    
    
    @timer("单线程")
    def single_thread(func, type=""):
        for i in range(10):
            func()
    
    
    
    # 单线程
    single_thread(count, type="CPU计算密集型")
    single_thread(io_disk, type="磁盘IO密集型")
    single_thread(io_web, type="网络IO密集型")
    single_thread(io_simulation, type="模拟IO密集型")
    
    
    # 多线程
    # 被装饰函数
    from threading import Thread
    
    
    @timer("多线程")
    def multi_thread(func, type=''):
        thread_list = []
        for i in range(10):
            t = Thread(target=func, args=())
            thread_list.append(t)
            t.start()
        e = len(thread_list)
        while True:
            for thred in thread_list:
                if not thred.is_alive():
                    e -= 1
            if e <= 0:
                break
    
    
    # 多线程
    multi_thread(count, type="CPU计算密集型")
    multi_thread(io_disk, type="磁盘IO密集型")
    multi_thread(io_web, type="网络IO密集型")
    multi_thread(io_simulation, type="模拟IO密集型")
    
    
    # 多进程
    # 被修饰函数
    from multiprocessing import Process
    
    
    @timer("多线程")
    def multi_process(func, type=""):
        process_list = []
        for x in range(10):
            p = Process(target=func, args=())
            process_list.append(p)
            p.start()
        e = process_list.__len__()
    
        while True:
            for pr in process_list:
                if not pr.is_alive():
                    e -= 1
            if e <= 0:
                break
    
    # 多进程
    multi_process(count, type="CPU计算密集型")
    multi_process(io_disk, type="磁盘IO密集型")
    multi_process(io_web, type="网络IO密集型")
    multi_process(io_simulation, type="模拟IO密集型")
    

    由于自己的电脑是单核CPU,故多进程结果无法展示,请读者见谅,谢谢!


    结果.png

    3.结论

    • 1.对于CPU密集型任务,多线程与单线程对比时,不仅没有优势,还由于要不断的加锁与释放GIL全局锁,切换线程而浪费大量时间,效率低;多进程,由于是多个cpu同时进行计算,效率成倍增加。
    • 2.对于IO密集型任务(磁盘IO、网络IO、数据库IO等),计算量小,主要是IO等待时间的浪费,多线程对比单线程也没能体现很大的优势,这是由于上述的IO任务不够繁杂,所以优势不明显。
    • 3.模拟IO密集型任务,用sleep来模型IO等待时间,为了体现多线程的优势。单个线程需要每个线程都要sleep(2),10个线程就要20秒;而对线程,在sleep(2)时,会切换到其他线程,使得10个线程同时sleep(2),最终10个线程只需要2秒。
    • 4.单线程总是最慢,多进程总是最快。多线程适合在IO密集任务下使用(如网络爬虫、网站开发等),多进程适合在对CPU计算要求较高的任务下使用(如数据分析、机器学习等);多进程虽然总是最快,但不一定是最优的选择,因为它需要CPU资源支持下才能体现优势。

    4.参考文章

    python编程时光
    win7系统,笔记本电脑查看是几核CPU方法

    相关文章

      网友评论

          本文标题:python3并发编程基础

          本文链接:https://www.haomeiwen.com/subject/pmosjqtx.html