Skip to content

Commit

Permalink
fix: clean up thread correctly to avoid memory leak
Browse files Browse the repository at this point in the history
  • Loading branch information
maartenbreddels committed Dec 15, 2023
1 parent c776c2e commit 18b1cfa
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
5 changes: 5 additions & 0 deletions solara/server/kernel_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,11 @@ def set_context_for_thread(context: VirtualKernelContext, thread: threading.Thre
current_context[key] = context


def clear_context_for_thread(thread: threading.Thread):
key = get_thread_key(thread)
current_context.pop(key, None)


def has_current_context() -> bool:
thread_key = get_current_thread_key()
return (thread_key in current_context) and (current_context[thread_key] is not None)
Expand Down
15 changes: 11 additions & 4 deletions solara/server/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,17 +258,24 @@ def WidgetContextAwareThread__init__(self, *args, **kwargs):


def Thread_debug_run(self):
if not hasattr(self, "current_context"):
# this happens when a thread was running before we patched
return Thread__run(self)
if self.current_context:
kernel_context.set_context_for_thread(self.current_context, self)
shell = self.current_context.kernel.shell
shell.display_pub.register_hook(shell.display_in_reacton_hook)
display_pub = self.current_context.kernel.shell.display_pub
display_in_reacton_hook = self.current_context.kernel.shell.display_in_reacton_hook
display_pub.register_hook(display_in_reacton_hook)
try:
context = self.current_context or solara.util.nullcontext()
with pdb_guard(), context:
Thread__run(self)
finally:
if self.current_context:
shell.display_pub.unregister_hook(shell.display_in_reacton_hook)
current_context = self.current_context
self.current_context = None
kernel_context.clear_context_for_thread(self)
if current_context:
display_pub.unregister_hook(display_in_reacton_hook)


_patched = False
Expand Down

0 comments on commit 18b1cfa

Please sign in to comment.