Python 线程和异步

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值