Andrew Svetlov <andrew.svet...@gmail.com> added the comment:

Perhaps Kyle is right, I had a misunderstanding with `get_running_loop()` vs 
`_get_running_loop()`.

The last version seems good except for the rare chance of race condition.

The safe code can look like:

global_lock = threading.Lock()  like GIL

       def _get_loop(self):
           loop = asyncio.get_running_loop()
           if self._loop is None:
                # the lock is required because
                # the thread switch can happen
                # between `self._loop is None` check
                # and `self._loop = loop` assignment
                with global_lock:
                    if self._loop is not None:
                        self._loop = loop
           if loop is not self._loop: raise

The alternative is using the fast C atomic `compare_and_swap` function
which is executed under the hold GIL.
We need the pure-Python fallback anyway.

Multithreading is hard...

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue42392>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to