- 是的,它屈服于事件循环。
在 asyncio 的源代码中:
async def open_connection(host=None, port=None, *,
limit=_DEFAULT_LIMIT, **kwds):
"""A wrapper for create_connection() returning a (reader, writer) pair.
The reader returned is a StreamReader instance; the writer is a
StreamWriter instance.
The arguments are all the usual arguments to create_connection()
except protocol_factory; most common are positional host and port,
with various optional keyword arguments following.
Additional optional keyword arguments are loop (to set the event loop
instance to use) and limit (to set the buffer limit passed to the
StreamReader).
(If you want to customize the StreamReader and/or
StreamReaderProtocol classes, just copy the code -- there's
really nothing special here except some convenience.)
"""
loop = events.get_running_loop()
reader = StreamReader(limit=limit, loop=loop)
protocol = StreamReaderProtocol(reader, loop=loop)
transport, _ = await loop.create_connection(
lambda: protocol, host, port, **kwds)
writer = StreamWriter(transport, protocol, reader, loop)
return reader, writer
它调用loop.create_connection 这也是await 调用,大约是loop.create_connection:
此方法将尝试在后台建立连接。成功时,它返回一个(传输,协议)对。
Docs 说。所以它然后将控制权交给事件循环并让其他协程运行,而之前的协程正在await 中等待建立连接。
- 如果您绝对确定要阻止正在运行事件循环的线程,那么您可以只使用低级别的socket。老实说,我真的反对这个想法,因为没有太多理由这样做。
只是一个小补充,我看到你不接受你以前问题的答案。人们写答案花费自己的时间和精力来帮助其他人。如果答案解决了您的问题,那么将它们标记为答案是感谢他们努力的一种方式!更多提示请参考Stackoverflow tour!