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.youkuaiyun.com/') as resp:
        response = resp.status
    return response


def get_request_normal():
    resp = requests.request('GET', 'https://www.youkuaiyun.com/')
    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

### Python线程异步编程的概念 #### 线程 (Threading) 在Python中,多线程是一种并发执行模型,允许程序在同一进程中运行多个线程。每个线程都可以独立于其他线程执行特定的任务。然而,由于全局解释器锁(GIL),Python中的多线程并不适合CPU密集型任务,但对于I/O密集型操作则非常有效[^1]。 ```python import threading def task(name): print(f"Task {name} started.") # Simulate I/O-bound operation with sleep. time.sleep(2) print(f"Task {name} finished.") threads = [] for i in range(5): thread = threading.Thread(target=task, args=(i,)) threads.append(thread) thread.start() for thread in threads: thread.join() ``` 这段代码展示了如何创建并启动五个线程来执行`task`函数。每个线程都模拟了一个耗时的操作,并最终完成任务。 #### 异步编程 (Asynchronous Programming) 相比之下,异步编程利用事件循环协程来管理并发操作。这种方式不需要显式的线程切换机制,而是依赖于操作系统调度以及底层库的支持。对于大量的网络请求或其他形式的阻塞调用来说,这种方法能够显著提高效率[^3]。 ```python import asyncio async def async_task(name): print(f"Async Task {name} started.") await asyncio.sleep(2) # Non-blocking call to simulate an IO-bound operation. print(f"Async Task {name} finished.") async def main(): tasks = [async_task(i) for i in range(5)] await asyncio.gather(*tasks) asyncio.run(main()) ``` 这里定义了一个名为 `main()` 的异步函数,在其中创建了五个不同的异步任务实例并通过 `gather()` 方法一起等待它们全部完成后结束整个过程。 ### 使用方法的区别 当涉及到具体的应用场景时: - **线程** 更适用于那些需要真正意义上的并行计算的情况,比如文件读写、数据库查询等I/O密集型工作负载; - **异步编程** 则更适合处理大量短时间内的频繁交互式任务,例如Web服务器响应HTTP请求或是WebSocket通信等非阻塞性的工作流; 两者之间的主要差异在于实现原理上——前者基于传统的OS级线程池分配资源给各个子任务去跑;后者则是依靠单一线程内通过协作式多任务的方式来达到类似的效果,从而减少了上下文切换带来的开销[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值