每连接一线程要几个线程
按模型,5 个连接下 threads_needed("thread", 5, 2) 交回几?
贯穿本节的并发模型(判题机 0.25 核有 GIL、答案不靠时序,这是它的确定模型,见 spine.py):高并发服务器搭起来后要选架构、加锁护状态、连接池/队列、压测、测吞吐延迟、定位竞争。
架构:MODELS=thread(每连接一线程)/pool(固定线程池)/async(单事件循环);threads_needed=撑起连接要几个线程、scales_cheap=扩起来省不省。
MODELS = ["thread", "pool", "async"]
def n_models():
"""常见的高并发服务器架构有几种。"""
return len(MODELS)
def threads_needed(model, conns, workers):
"""撑起这些连接各要几个线程:thread 每连接一个、pool 固定 worker、async 一个事件循环。"""
if model == "thread":
return conns
if model == "pool":
return workers
return 1
def scales_cheap(model):
"""这种架构扩起来省不省(线程/连接开销大;池和异步省)。"""
return model in ("pool", "async")
print(threads_needed("thread", 5, 2))
全部评论