]> gerrit.simantics Code Review - simantics/python.git/commitdiff
Mind the threads in writeSCL. 18/318/1
authortkorvola <Timo.Korvola@vtt.fi>
Wed, 1 Feb 2017 17:48:01 +0000 (19:48 +0200)
committertkorvola <Timo.Korvola@vtt.fi>
Wed, 1 Feb 2017 17:50:45 +0000 (19:50 +0200)
Both JNIEnv and PyThreadState are per thread.  So check that we are
in the main thread before messing with JNIEnv.  Writes from other
threads (possibly created in Python) are just dropped; those seem
difficult to do right.

Also unlock GIL while calling the Java method.

Change-Id: I49a447e22ba4411800445f7149f5bc257a082e4f

org.simantics.pythonlink.win32.x86_64/jnipython.dll
org.simantics.pythonlink.win32.x86_64/src/sclpy.c

index e5339466a7dc2c6854d07f4d9b6f02b02425d111..ab792ab08a7ca26dd2a50f39b3abb8bc2f709548 100644 (file)
Binary files a/org.simantics.pythonlink.win32.x86_64/jnipython.dll and b/org.simantics.pythonlink.win32.x86_64/jnipython.dll differ
index 686221e2ac09da96874dc03c7c5abb857495b2e2..428a45a35667fe34fcf70b0f0baae0f465c53557 100644 (file)
@@ -53,19 +53,26 @@ writeToSCL(PyObject *self, PyObject *args)
                Py_UNICODE *what;
                Py_ssize_t length;
                if (!PyArg_ParseTuple(args, "u#", &what, &length))
-                       return Py_BuildValue("");
+                       Py_RETURN_NONE;
 
                {
-               jclass writerClass = (*env)->FindClass(env, WRITER_CLASS);
-               jmethodID writeMethod = (*env)->GetMethodID(env, writerClass, "write", "([CII)V");
-               jcharArray chars = (*env)->NewCharArray(env, (jsize)length);
-
-               (*env)->SetCharArrayRegion(env, chars, 0, length, what);
-               (*env)->CallVoidMethod(env, sclWriter, writeMethod, chars, 0, length);
+                       PyThreadState *my_ts = PyThreadState_Get();
+                       if (my_ts == main_ts) {
+                               jclass writerClass = (*env)->FindClass(env, WRITER_CLASS);
+                               jmethodID writeMethod = (*env)->GetMethodID(env, writerClass, "write", "([CII)V");
+                               jcharArray chars = (*env)->NewCharArray(env, (jsize)length);
+
+                               (*env)->SetCharArrayRegion(env, chars, 0, length, what);
+                               Py_BEGIN_ALLOW_THREADS
+                               (*env)->CallVoidMethod(env, sclWriter, writeMethod, chars, 0, length);
+                               Py_END_ALLOW_THREADS
+                       } else {
+                               //TODO
+                       }
                }
     }
 
-    return Py_BuildValue("");
+       Py_RETURN_NONE;
 }
 
 static PyMethodDef sclWriterMethods[] = {