Skip to content

Commit dedf571

Browse files
committed
AsyncioConnection: fix initialize_reactor when called in event loop
Previously, if executed within existing asyncio loop, driver would take the loop, assume it's not used and start it in a separate thread. Additionally, if executed outside of loop, driver would create a new one and make it default for calling thread. Those behaviors are wrong so they are changed. Now driver creates its own loop and executes it in a thread. Code that handled pid changes, which can happen when class is transferred using e.g. multiprocessing, is fixed too - previously it didn't create new thread after such transition.
1 parent cdd125a commit dedf571

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

cassandra/io/asyncioreactor.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -113,15 +113,17 @@ def __init__(self, *args, **kwargs):
113113
def initialize_reactor(cls):
114114
with cls._lock:
115115
if cls._pid != os.getpid():
116+
# This means that class was passed to another process,
117+
# e.g. using multiprocessing.
118+
# In such case the class instance will be different and passing
119+
# tasks to loop thread won't work.
120+
# To fix we need to re-initialize the class
116121
cls._loop = None
122+
cls._loop_thread = None
123+
cls._pid = os.getpid()
117124
if cls._loop is None:
118-
try:
119-
cls._loop = asyncio.get_running_loop()
120-
except RuntimeError:
121-
cls._loop = asyncio.new_event_loop()
122-
asyncio.set_event_loop(cls._loop)
123-
124-
if not cls._loop_thread:
125+
assert cls._loop_thread is None
126+
cls._loop = asyncio.new_event_loop()
125127
# daemonize so the loop will be shut down on interpreter
126128
# shutdown
127129
cls._loop_thread = Thread(target=cls._loop.run_forever,

0 commit comments

Comments
 (0)