Python:EventLoop
asyncio 에 사용되는 이벤트 루프.
Python Concurrency Mind Maps
|
스레드 또는 프로세스 풀에서 코드를 실행하기
awaitable loop.run_in_executor(executor, func, *args)
지정된 실행기에서 func 가 호출되도록 배치합니다.
loop.set_default_executor(executor)
Set executor as the default executor used by run_in_executor(). executor must be an instance of ThreadPoolExecutor.
파일 기술자 관찰하기
이 메서드의 일부 제한 사항은 플랫폼 지원 절을 참조하십시오.
loop.add_reader(fd, callback, *args)
fd 파일 기술자가 읽기 가능한지 관찰하기 시작하고, 일단 fd가 읽기 가능해지면 지정한 인자로 callback 을 호출합니다.
예제는 다음과 같다:
import asyncio
import urllib.parse
import sys
import pdb
import os
def fileCallback(*args):
print("Received: " + sys.stdin.readline())
loop = asyncio.get_event_loop()
task = loop.add_reader(sys.stdin.fileno(), fileCallback)
loop.run_forever()
loop.remove_reader(fd)
Stop monitoring the fd file descriptor for read availability. Returns True if fd was previously being monitored for reads.
loop.add_writer(fd, callback, *args)
fd 파일 기술자가 쓰기 가능한지 관찰하기 시작하고, 일단 fd가 쓰기 가능해지면 지정한 인자로 callback 을 호출합니다.
callback 에 키워드 인자를 전달하려면 functools.partial()를 사용하십시오.
아래와 같은 느낌이다.
loop.remove_writer(fd)
쓰기 가용성에 대한 fd 파일 설명자 모니터링을 중지합니다. fd가 이전에 쓰기를 모니터링하고 있었으면 True를 반환합니다.
How to await a select.select call in python asyncio
You could use #loop.add_reader to wait for the read availability of your socket:
async def watch(fd):
future = asyncio.Future()
loop.add_reader(fd, future.set_result, None)
future.add_done_callback(lambda f: loop.remove_reader(fd))
await future
async def run(self):
while True:
await watch(self._q._connection)
msg = self._q.receive()
print(msg)
However, it'll be very tricky to avoid all the blocking IO calls of the library you mentioned without rewriting it completely. Instead, I'd recommend to use the #loop.run_in_executor method to schedule the blocking IO calls in a thread pool:
async def run(self):
loop = asyncio.get_event_loop()
while True:
msg = await loop.run_in_executor(None, self._q.receive)
print(msg)
Python:selectors 에 I/O 다중화를 구성하고 싶다면
import asyncio
import selectors
selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)