找到你要的答案

Q:How to write custom event loop policy?

Q:如何写自定义事件循环策略?

I'm researching the asyncio library and I cannot understand completely the reason behind event loop policies.

So far it's clear that this interface is a factory that returns event loop for current context. The definition of the context is not clear though. Apparently, the interface of asyncio.AbstractEventLoopPolicy assumes that concrete implementation will be able to extract context on its own because neither method accepts arguments. This model works well for the event-loop-per-thread default policy, but usage under more sophisticated circumstances are under the question.

Looks like context isn't an arbitrary entity, but should follow certain rules (e.g. being visible globally). I wonder if such rules are listed anywhere. Are there examples of custom policies around?

我研究的asyncio图书馆和我完全听不懂在事件循环政策的原因。

到目前为止,很明显这个接口是一个返回当前上下文的事件循环的工厂。上下文的定义是不明确的,虽然。显然,对asyncio.abstracteventlooppolicy界面假设具体的实施将能够提取上下文自己因为没有方法接受参数。此模型适用于每线程默认策略的事件循环,但在更复杂的情况下使用的问题下。

看起来上下文不是一个任意的实体,但应该遵循一定的规则(例如在全球可见)。我不知道这些规则是否列在任何地方。是否有定制政策的例子?

answer1: 回答1:

Custom policy is required when you implement non-default event loop.

The main problem is: I want to create new event loop by asyncio.new_event_loop(). It's required for threads: only main thread has implicit event loop, all other threads should instantiate loop explicitly.

But I don't know specific event loop type, thus I need a factory for loop creation -- pluggable event loop policy.

在执行非默认事件循环时需要自定义策略。

主要的问题是:我想asyncio创建新的事件循环。new_event_loop()。这是所需的线程:只有主线程有隐含的事件循环,所有其他的线程应该实例化环式。

但我不知道具体的事件循环型,因此我需要一个循环的创建工厂可插拔事件循环政策。

python  python-3.x  python-asyncio