Warm tip: This article is reproduced from stackoverflow.com, please click
python-3.x python-asyncio python-multithreading concurrent.futures

Can concurrent.futures.Future be converted to asyncio.Future?

发布于 2020-03-28 23:15:58

I'm practicing asyncio after writing multithreaded code many years.

Noticed something which i find it strange. Both in asyncio and in concurrent there is a Future object.

from asyncio import Future
from concurrent.futures import Future

Guess each onee has it's own role..

My question is if i can transfer concurrent.future.Future to asyncio.Future (or the opposite)?

Questioner
Aaron_ab
Viewed
49
Mikhail Gerasimov 2019-01-09 03:51

concurrent.futures.Future is an object we use to write asynchronous code based on OS threads or OS processes alongside with other things concurrent.futures module provides us with.

asyncio.Future is an object we use to write asynchronous code based on coroutines and things asyncio module provides us with.

In other words concurrent.futures and asyncio try to solve same task, but in a different ways. Solving same task means that many things would be similar in thread/process-based approach and coroutine-based approach. For example take a look at asyncio.Lock and threading.Lock - similar, but different.

Is transition between different such similar object possible? No it's not.

Essential difference between asyncio and thread-based modules makes cooperation unable:

  • In asyncio you should await things to suspend execution flow and allow other coroutines to be executed meanwhile.

  • In thread-based modules execution flow is suspended by suspending whole thread.

For example, when you write thread-based code you write:

future = concurrent.futures.Future()
# ...
result = future.result()  # acts like time.sleep blocking whole thread

But in asyncio you shouldn't block thread, you should return control to event loop:

future = asyncio.Future()
# ...
result = await future  # block current execution flow returning control to event loop 
                       # without blocking thread,
                       # current flow will be resumed later