[issue31960] Protection against using a Future with another loop only works with await

Yury Selivanov report at bugs.python.org
Tue Nov 7 09:31:53 EST 2017


Yury Selivanov <yselivanov at gmail.com> added the comment:

> On the other hand, the Future implementation is entirely not thread-safe (btw, the constructor optimistically claims the done callbacks are scheduled using call_soon_threadsafe(), but the implementation actually calls call_soon()).

This is weird.  PEP 3156 specifies that Future uses call_soon.  The implementation uses call_soon.  And it actually makes sense to use call_soon for Futures.  

Situations when Future.cancel() or Future.set_result() is called from a different thread are extremely rare, so we want to avoid the overhead of using call_soon_threadsafe().  Moreover, I bet there are many other cases where Future implementation is not threadsafe.

If one absolutely needs to call Future.set_result() from a different thread, they can always do `loop.call_soon_threadsafe(fut.set_result, ...)`.

My opinion on this: update documentation for all Python versions to reflect that Future uses call_soon.

> Do you think it would be fine for Future._schedule_callbacks() to check the event loop is the current one, or do you think it would impact performance too much (or perhaps it is simply not desirable)?

I think we should update `Future._schedule_callbacks` to check if the loop is in debug mode.  If it is call `loop._check_thread()`, which will raise a RuntimeError if the current thread is different from the one that the loop belongs to.  

This will have no detectable overhead, but will ease debugging of edge cases like writing multithreaded asyncio applications.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue31960>
_______________________________________


More information about the Python-bugs-list mailing list