其他分享
首页 > 其他分享> > day37_步入百万年薪的第三十七天——阻塞、非阻塞、同步、异步

day37_步入百万年薪的第三十七天——阻塞、非阻塞、同步、异步

作者:互联网

day37

阻塞、非阻塞、同步、异步

进程运行的三个状态:运行、就绪、阻塞

执行的角度
提交任务的角度

案例:给三个老师发布任务:

同步调用、异步调用

同步调用
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import time
import random
import os


def task(i):
    print(f"{os.getpid()} 开始了")
    time.sleep(random.randint(1, 3))
    print(f"{os.getpid()} 结束了")
    return i


if __name__ == '__main__':
    pool = ProcessPoolExecutor(4)
    for i in range(6):
        obj = pool.submit(task, i)
        # obj是一个动态对象,返回当前对象的状态,有可能运行中(running),可能pending(就绪或阻塞),还可能使结束了(finished returned int)
        # obj.result()必须等到这个任务完成后,返回结果之后再执行下一个任务
        print(obj.result())   # obj.result()没有返回值
    pool.shutdown(wait=True)
    print("===主")
异步调用

异步调用返回值如何接收? 未解决

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import time
import random
import os


def task(i):
    print(f"{os.getpid()} 开始了")
    time.sleep(random.randint(1, 3))
    print(f"{os.getpid()} 结束了")
    return i


if __name__ == '__main__':
    pool = ProcessPoolExecutor(4)
    for i in range(6):
        pool.submit(task, i)
        
    pool.shutdown(wait=True)
    # shutdown:让我的主进程等待进程池中所有的子进程都结束之后再执行下面的代码,优点类似于join
    # shutdown:在上一个进程池没有完成所有的任务之前,不允许添加新的任务
    # 一个任务是通过一个函数实现的,任务完成了他的返回值就是函数的返回值
    print("===主")

方式一:异步调用统一接收结果

缺点:我不能马上收到任何一个已经完成的任务的返回值,我只能等到所有的任务全部结束之后统一回收

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import time
import random
import os


def task(i):
    print(f"{os.getpid()} 开始了")
    time.sleep(random.randint(1, 3))
    print(f"{os.getpid()} 结束了")
    return i


if __name__ == '__main__':
    pool = ProcessPoolExecutor(4)
    lst = []
    for i in range(6):
        obj = pool.submit(task, i)
        lst.append(obj)
    pool.shutdown()
    for i in lst:
        i.result()  # print(i.result())
    print("===主")

第二种方式:异步调用+回调函数

异步调用+回调函数

浏览器工作原理
爬虫的工作原理
import requests
ret = requests.get("http://www.baidu.com")
if ret.status_code == 200:
    print(ret.text)
版本一

主代码

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import requests


def task(url):
    """
    模拟的是爬取多个源代码,一定有IO操作
    :param url:
    :return:
    """
    ret = requests.get(url)
    if ret.status_code == 200:
        return ret.text


def parse(content):
    """
    模拟对数据进行分析,一般没有IO
    :param content:
    :return:
    """
    return len(content)


if __name__ == '__main__':
    # 串行 耗费时间长,不可取
    # ret1 = task("http://www.baidu.com")
    # print(parse(ret1))
    # ret2 = task("http://www.JD.com")
    # print(parse(ret2))
    # ret3 = task("http://www.taobao.com")
    # print(parse(ret3))
    # ret4 = task("https://www.cnblogs.com/jin-xin/articles/7459977.html")
    # print(parse(ret4))

    # 开启线程池,并发并行的执行
    url_list = [
        "http://www.baidu.com",
        "http://www.JD.com",
        "http://www.taobao.com",
        "https://www.cnblogs.com/jin-xin/articles/7459977.html",
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/9811379.html',
        'https://www.cnblogs.com/jin-xin/articles/11245654.html',
        'https://www.luffycity.com/'
    ]
    pool = ThreadPoolExecutor(4)
    obj_list = []
    for url in url_list:
        obj = pool.submit(task, url)
        obj_list.append(obj)

    pool.shutdown(wait=True)
    for i in obj_list:
        print(parse(i.result()))
    print("===主")

总结:

缺点:

版本二

针对版本一的缺点2进行改进,让串行变成并发或并行

解决方式

主代码

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import requests


def task(url):
    """
    模拟的是爬取多个源代码,一定有IO操作
    :param url:
    :return:
    """
    ret = requests.get(url)
    if ret.status_code == 200:
        return parse(ret.text)


def parse(content):
    """
    模拟对数据进行分析,一般没有IO
    :param content:
    :return:
    """
    return len(content)


if __name__ == '__main__':
    url_list = [
        "http://www.baidu.com",
        "http://www.JD.com",
        "http://www.taobao.com",
        "https://www.cnblogs.com/jin-xin/articles/7459977.html",
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/9811379.html',
        'https://www.cnblogs.com/jin-xin/articles/11245654.html',
        'https://www.luffycity.com/'
    ]
    pool = ThreadPoolExecutor(4)
    obj_list = []
    for url in url_list:
        obj = pool.submit(task, url)
        obj_list.append(obj)

    pool.shutdown(wait=True)
    for i in obj_list:
        print(i.result())
    print("===主")

总结:

版本一与版本二对比

版本一:

版本二:

缺点:

版本三

基于异步调用回收所有任务的结果我要做到实时回收结果

并发执行任务每个任务只是处理IO阻塞的,不能增加新的功能

异步调用+回调函数

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import requests


def task(url):
    """
    模拟的是爬取多个源代码,一定有IO操作
    :param url:
    :return:
    """
    ret = requests.get(url)
    if ret.status_code == 200:
        return ret.text


def parse(obj):
    """
    模拟对数据进行分析,一般没有IO
    :param content:
    :return:
    """
    print(len(obj.result()))


if __name__ == '__main__':
    url_list = [
        "http://www.baidu.com",
        "http://www.JD.com",
        "http://www.taobao.com",
        "https://www.cnblogs.com/jin-xin/articles/7459977.html",
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/7459977.html',
        'https://www.cnblogs.com/jin-xin/articles/9811379.html',
        'https://www.cnblogs.com/jin-xin/articles/11245654.html',
        'https://www.luffycity.com/'
    ]
    pool = ThreadPoolExecutor(4)
    for url in url_list:
        obj = pool.submit(task, url)
        obj.add_done_callback(parse)

总结:

异步与回调是一回事?

标签:__,www,obj,day37,阻塞,第三十七,https,print,com
来源: https://www.cnblogs.com/NiceSnake/p/11432224.html