异步调用与回调机制

Posted Claire_xu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异步调用与回调机制相关的知识,希望对你有一定的参考价值。

 

提交任务的两种方式。

同步调用:提交完任务后,就在原地等待任务执行完毕,拿到结果,再执行下一行代码,导致程序是串行执行

异步调用:提交完任务后,不等待任务执行完毕

 

from concurrent.futures import ThreadPoolExecutor
import time,random

def la(name):
    print(\'%s is laing\'%name)
    time.sleep(random.randint(3,5))
    res = random.randint(7,13)*\'#\'
    return {\'name\':name,\'res\':res}

def weigh(shit):
    shit = shit.result() # 异步回掉时,处理接收到的对象
    name = shit[\'name\']
    size = len(shit[\'res\'])
    print(\'%s 拉了 《%s》kg\'%(name,size))

if __name__ ==\'__main__\':
    pool = ThreadPoolExecutor(13)

    # 同步调用
    # shit1 = pool.submit(la,\'alex\').result()
    # weigh(shit1)
    # shit2 = pool.submit(la, \'huhao\').result()
    # weigh(shit2)
    # shit3 = pool.submit(la, \'zhanbin\').result()
    # weigh(shit3)

    # 异步调用
    pool.submit(la, \'alex\').add_done_callback(weigh)
    pool.submit(la, \'huhao\').add_done_callback(weigh)
    pool.submit(la, \'zhanbin\').add_done_callback(weigh)

 

简单网页爬虫示例:

import requests,time
from concurrent.futures import ThreadPoolExecutor

def get(url):
    print(\'get url\',url)
    response = requests.get(url)
    time.sleep(3)
    return {\'url\':url,\'content\':response.text}

def parse(res):
    res = res.result()
    print(\'%s parse res is %s\'%(res[\'url\'],len(res[\'content\'])))

if __name__ == \'__main__\':
    urls = [
        \'http://www.cnblogs.com/stin\',
        \'https://www.python.org\',
        \'https://www.openstack.org\',
    ]
    pool = ThreadPoolExecutor(2)
    for url in urls:
        pool.submit(get,url).add_done_callback(parse)

 

以上是关于异步调用与回调机制的主要内容,如果未能解决你的问题,请参考以下文章

异步调用与回调机制

5.1.23 异步调用与回调机制

java回调机制(老板与员工例子)

阿里P7大神:深入理解Java回调机制总结(同步回调/异步回调)

简单理解函数回调——同步回调与异步回调

并发编程 - 线程 - 1.线程queue/2.线程池进程池/3.异步调用与回调机制