Python 线程和异步

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/EDS95/article/details/84439659

Python 线程和异步

  • 线程: cpu切换上下文
  • 协程: 用户切换上下文
     

Description:

Example:

  • io 处理
#!/usr/bin/env python
# coding: utf-8


from timeit import timeit
import asyncio
import requests
from threading import Thread
import aiohttp


def call_normal():
    response = [get_request_normal() for _ in range(10)]


def call_threaded():
    threads = [Thread(target=get_request_normal) for _ in range(10)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()


def call_async():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(async_request(loop))


async def async_request(loop):
    client = aiohttp.ClientSession(loop=loop)
    request_tasks = [request_fetch(client) for _ in range(10)]
    responses = await asyncio.gather(*request_tasks)
    await client.close()
    return responses


async def request_fetch(client):
    async with client.get('https://www.csdn.net/') as resp:
        response = resp.status
    return response


def get_request_normal():
    resp = requests.request('GET', 'https://www.csdn.net/')
    return resp.status_code


if __name__ == '__main__':
    a = timeit(call_normal, number=5)
    print('normal:', a)
    b = timeit(call_threaded, number=5)
    print('threaded:', b)
    c = timeit(call_async, number=5)
    print('async:', c)

image

  • cpu 处理

Remakes:

reference:

Asynchronous Python
Async Through the Looking Glass

猜你喜欢

转载自blog.csdn.net/EDS95/article/details/84439659