2015-09-15 10 views
7

スレッドからasyncioイベントループにジョブをサブミットしたい(ちょっとrun_in_executorと同じですが、その逆です)。ここでasyncioイベントループにジョブを提出する

asyncioドキュメントはconcurrency and multithreadingについて言っているのです:

別のスレッドからのコールバックをスケジュールするには、BaseEventLoop.call_soon_threadsafe()メソッドを使用する必要があります。 loop.call_soon_threadsafe(asyncio.async, coro_func())

正常に動作しますが、コルーチンの結果が失われた:別のスレッドからコルーチンをスケジュールする 例。

代わりに、スレッドがconcurrent.futures.Futureを通じて結果にアクセスできるようにasync(またはensure_future)によって返された未来に行って、コールバックを追加する機能を使用することが可能です。

このような機能が標準ライブラリに実装されていない特定の理由はありますか?あるいは、私はそれを達成するためのより簡単な方法が欠けていましたか?

答えて

6

私のリクエストはrun_coroutine_threadsafeの機能が実装されましたhereです。

例:あなたがそれそう質問でこれを入れたいん

class LoopExecutor(concurrent.futures.Executor): 
    """An Executor subclass that uses an event loop 
    to execute calls asynchronously.""" 

    def __init__(self, loop=None): 
     """Initialize the executor with a given loop.""" 
     self.loop = loop or asyncio.get_event_loop() 

    def submit(self, fn, *args, **kwargs): 
     """Schedule the callable, fn, to be executed as fn(*args **kwargs). 
     Return a Future object representing the execution of the callable.""" 
     coro = asyncio.coroutine(fn)(*args, **kwargs) 
     return asyncio.run_coroutine_threadsafe(coro, self.loop) 
+0

のdoesnt:

def target(loop, timeout=None): future = asyncio.run_coroutine_threadsafe(add(1, b=2), loop) return future.result(timeout) async def add(a, b): await asyncio.sleep(1) return a + b loop = asyncio.get_event_loop() future = loop.run_in_executor(None, target, loop) assert loop.run_until_complete(future) == 3 

私はもともとまだとして実装することができconcurrent.futures.Executorのサブクラスを投稿答えのように見える –

+0

同じことを達成するためのより良い方法があるかもしれないので、それは一種の[自分の質問に対する部分的な答え](http://stackoverflow.com/help/self-answer)です。 – Vincent

+0

あなたがそのように表示された場合、ok :) –

関連する問題