Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Python backgrounds threads to run in parallel with R #1641

Merged
merged 15 commits into from
Aug 10, 2024

Conversation

t-kalinowski
Copy link
Member

@t-kalinowski t-kalinowski commented Aug 4, 2024

This PR allows spawned Python background threads to run while the main thread is executing R code.

For example, if you start a Python background thread like this:

library(reticulate)

py_config()

py_run_string(r"---(
import _thread
from time import sleep, localtime, strftime

def be_chatty():
  for i in range(100000):
    print('Hi', strftime('%H:%M:%S', localtime()))
    sleep(1)

_thread.start_new_thread(be_chatty, ())

)---")

With the current reticulate release, we don't see any output from the Python thread while at the R repl. The Python thread only is active while we are in a Python function that gives an opportunity for the GIL to be released (e.g, an explicit sleep, or evaluating Python bytecode). E.g., we only see output from the above background thread if we call in R:

py_sleep <- reticulate::import("time")$sleep
py_sleep(5)

However, with this PR, we now see output from the Python background thread even when not calling into Python from the main thread.

The primary motivation is to allow a Positron Python console to be backed by the same Python session reticulate in the Positron R console is using, without needing to block the R console, or spin-up+shutdown the ipykernel event loop on each call to repl_python().

@t-kalinowski t-kalinowski marked this pull request as ready for review August 8, 2024 01:35
@t-kalinowski t-kalinowski requested a review from kevinushey August 8, 2024 14:53
Copy link
Collaborator

@kevinushey kevinushey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

tests/testthat/test-python-threads.R Show resolved Hide resolved
@t-kalinowski t-kalinowski merged commit d683b3b into main Aug 10, 2024
16 checks passed
@t-kalinowski t-kalinowski deleted the allow-background-python-threads branch August 10, 2024 00:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants