Skip to content

Commit

Permalink
Make getting globals/locals thread safe
Browse files Browse the repository at this point in the history
  • Loading branch information
jmao-denver committed Sep 13, 2024
1 parent 321c553 commit e36c55b
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions src/main/c/jni/org_jpy_PyLib.c
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,7 @@ PyObject *getMainGlobals() {
}

pyGlobals = PyModule_GetDict(pyMainModule); // borrowed ref
JPy_INCREF(pyGlobals);

return pyGlobals;
}
Expand All @@ -532,7 +533,7 @@ JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getMainGlobals

JPy_BEGIN_GIL_STATE

globals = getMainGlobals(); // borrowed ref
globals = getMainGlobals(); // new ref
if (globals == NULL) {
goto error;
}
Expand All @@ -543,6 +544,7 @@ JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getMainGlobals
}

error:
JPy_XDECREF(globals);
JPy_END_GIL_STATE

return objectRef;
Expand All @@ -555,10 +557,12 @@ JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getCurrentGlobals

JPy_BEGIN_GIL_STATE

#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 12
globals = PyEval_GetFrameGlobals(); // new ref
#else
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION <= 12
globals = PyEval_GetGlobals(); // borrowed ref
JPy_INCREF(globals);
#else
// See https://peps.python.org/pep-0667 for the change in Python 3.13
globals = PyEval_GetFrameGlobals(); // new ref
#endif

if (globals == NULL) {
Expand All @@ -571,11 +575,9 @@ JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getCurrentGlobals
}

error:
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 12
JPy_XDECREF(globals);
#endif

JPy_END_GIL_STATE

return objectRef;
}

Expand All @@ -586,10 +588,12 @@ JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getCurrentLocals

JPy_BEGIN_GIL_STATE

#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 12
locals = PyEval_GetFrameLocals(); // new ref
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION <= 12
locals = PyEval_GetLocals(); // borrowed ref
JPy_INCREF(locals);
#else
locals = PyEval_GetLocals(); // borrowed ref
// See https://peps.python.org/pep-0667 for the change in Python 3.13
locals = PyEval_GetFrameLocals(); // new ref
#endif

if (locals == NULL) {
Expand All @@ -602,11 +606,9 @@ JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getCurrentLocals
}

error:
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 12
JPy_XDECREF(locals);
#endif

JPy_END_GIL_STATE

return objectRef;
}

Expand Down Expand Up @@ -919,7 +921,8 @@ jlong executeInternal(JNIEnv* jenv, jclass jLibClass, jint jStart, jobject jGlob

if (jGlobals == NULL) {
JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using main globals\n");
pyGlobals = getMainGlobals();
pyGlobals = getMainGlobals(); // new ref
decGlobals = JNI_TRUE;
if (pyGlobals == NULL) {
PyLib_HandlePythonException(jenv);
goto error;
Expand Down

0 comments on commit e36c55b

Please sign in to comment.